標籤:
首先建立項目看下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>();
或者
services.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();}
asp.net core 自訂中介軟體和service