asp.net core 自定義中間件和service


首先新建項目看下main方法:

public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}
main方法

其中,UseStartup<Startup>()方法使用了Startup類,在Startup類,有ConfigureServices和Configure方法,調用順序是先ConfigureServices后Configure。

 

下面生成自定義的Service:

public interface IMService
{
    string GetString();
}

public class MService:IMService
{
    public string GetString()
    {
        return "這是我的服務";
    }
}
View Code

可以在ConfigureServices中這樣使用:

services.AddSingleton<IMService, MService>();
或者
s
ervices.AddScoped<IMService, MService>();
或者
services.AddTransient<IMService, MService>();
這三個方法的作用都一樣,只是生成實例的方式不一樣,Singleton是所有的service都用單一的實例,Scoped 是一個請求一個實例,Transient 每次使用都是新實例。
也可以使用依賴注入的方式添加服務
public static class MServiceExtensions
{
    public static void AddMService(
           this IServiceCollection services)
    {
        services.AddScoped<IMService,MService>();
    }
}
View Code

這樣就可以在ConfigureServices中這樣用:services.AddMService();

 

下面自定義一個middleware

    public class MMiddleware
    {
        private RequestDelegate nextMiddleware;

        public MMiddleware(RequestDelegate next)
        {
            this.nextMiddleware = next;
        }

        public async Task Invoke(HttpContext context)
        {
            context.Items.Add("middlewareID",
                         "ID of your middleware");
            await this.nextMiddleware.Invoke(context);
        }
    }
View Code

同樣的,可以在Configure方法中這樣使用:app.UseMiddleware<MMiddleware>();

也可以

public static class MyMiddlewareExtensions
{
    public static IApplicationBuilder UseMMiddleware
              (this IApplicationBuilder app)
    {
        return app.UseMiddleware<MMiddleware>();
    }
}
就可以app.UseMMiddleware();


在controller中可以
public IActionResult Index()
{
    ViewBag.str= service.Getstring();
    ViewBag.MiddlewareID = HttpContext.Items["middlewareID"];
    return View();
}





 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM