ASP.NET Core 2.0 依赖注入
問題
如何使用?ASP.NET Core?服務(wù)容器進(jìn)行依賴注入?
答案
創(chuàng)建一個服務(wù)
public interface IGreetingService { ??string Greet(string to); }
public class GreetingService : IGreetingService { ?
? ??public string Greet(string to){ ? ? ? ?return $"Hello {to}";} }
然后可以在需要的時候注入,下面將此服務(wù)注入一個中間件(Middleware):
public class HelloWorldMiddleware { ?? ?private readonly RequestDelegate _next; ?
? ?public HelloWorldMiddleware(RequestDelegate next){_next = next;} ?
? ?public async Task Invoke(HttpContext context, IGreetingService greetingService){ ? ? ?
??var message = greetingService.Greet("World (via DI)"); ? await context.Response.WriteAsync(message);} }
使用此中間件的擴(kuò)展方法(IApplicationBuilder):
public static class UseMiddlewareExtensions { ? ?? ?public static IApplicationBuilder UseHelloWorld(this IApplicationBuilder app){ ? ? ? ?return app.UseMiddleware<HelloWorldMiddleware>();} }
下面需要將此服務(wù)添加到ASP.NET Core的服務(wù)容器中,位于Startup.cs文件的ConfigureServices()方法:
public void ConfigureServices(IServiceCollection services) {services.AddScoped<IGreetingService, GreetingService>(); }然后在請求管道中(request?pipeline)使用此中間件,位于Startup.cs文件的Configure()方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {app.UseHelloWorld(); }運(yùn)行,此時頁面輸出:
?
創(chuàng)建一個帶輸入?yún)?shù)的服務(wù)
如果你的服務(wù)需要更復(fù)雜的初始化參數(shù),下面我們創(chuàng)建一個FlexibleGreetingService:
? ?private readonly string _sayWhat; ?
??public FlexibleGreetingService(string sayWhat){_sayWhat = sayWhat;} ?
? ?public string Greet(string to){ ? ? ?
? ? ??return $"{_sayWhat} {to}";} }
我們可以使用AddScoped的一個重載工廠方法來添加此服務(wù)到容器中:
public void ConfigureServices(IServiceCollection services) {services.AddScoped<IGreetingService, FlexibleGreetingService>(factory =>{ ? ? ?return new FlexibleGreetingService("Hi");}); }
運(yùn)行,此時頁面輸出:
如果是單件生命周期,還有一個接受服務(wù)實例的重載方法:
public void ConfigureServices(IServiceCollection services) {services.AddSingleton<IGreetingService>(new FlexibleGreetingService("Hi ")); }?
討論
?ASP.NET Core內(nèi)置了一個輕量級的服務(wù)容器。我們可以在Startup.cs類的ConfigureServices()方法中配置需要的服務(wù)。這個方法在Configure()方法之前執(zhí)行,所以我們可以在任意中間件使用之前配置的服務(wù)(包含MVC服務(wù))。
依賴注入默認(rèn)是通過公開構(gòu)造函數(shù)來完成的,大多數(shù)情況下這是最佳實踐。
服務(wù)的生命周期
服務(wù)容器管理著添加到服務(wù)器列表的生命周期。下面列出了添加服務(wù)的三種方法:
-
AddScoped():服務(wù)會在一個請求內(nèi)部只創(chuàng)建一次。
-
AddTransient():服務(wù)會在每次需要時創(chuàng)建一次。
-
AddSingleton():服務(wù)會在第一次需要時創(chuàng)建一次,并在隨后保持不變。
注:EF的生命周期應(yīng)該是Scoped,我們可以通過IServiceCollection.AddDbContext來創(chuàng)建EF服務(wù)(內(nèi)部也是作為Scoped實現(xiàn))。
工廠方法
上面的方法都有一個重載方法來使用工廠方法來添加服務(wù)。對于需要復(fù)雜配置的服務(wù)這是很有用的。
這些方法的簽名看起來如下所示:
AddScoped(Func<IServiceProvider, TService>)框架提供的服務(wù)
ConfigureServices()接受的IServiceCollection參數(shù)擁有很多內(nèi)置的服務(wù)(由框架提供),可以參考ASP.NET Core文檔。
IServiceCollection有很多有用的擴(kuò)展方法來添加常用服務(wù),比如AddDbContext,AddIdentity,AddOptions和AddMvc。
銷毀服務(wù)
服務(wù)容器會自動調(diào)用所有實現(xiàn)了IDisposable接口的服務(wù)類型,除了那些作為實例(而不是類型)添加的服務(wù)。
獲取服務(wù)(Request?Services)
盡管通過構(gòu)造函數(shù)來注入服務(wù)被認(rèn)為是最佳實踐,我們依然可以通過IServiceProvider的GetService方法來獲取服務(wù)。在中間件中IServiceProvider對象可以通過HttpContext來獲取:
public async Task Invoke(HttpContext context) { ??var greetingService = context.RequestServices.GetService<IGreetingService>(); ? ?var message = greetingService.Greet("World (via GetService)"); ?
?await context.Response.WriteAsync(message); }
注:需要添加Microsoft.Extensions.DependencyInjection引用才能上述使用GetService的泛型重載方法。
運(yùn)行,此時頁面輸出:
原文地址:http://www.cnblogs.com/sanshi/p/7705617.html
.NET社區(qū)新聞,深度好文,微信中搜索dotNET跨平臺或掃描二維碼關(guān)注
總結(jié)
以上是生活随笔為你收集整理的ASP.NET Core 2.0 依赖注入的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Entity Framework Cor
- 下一篇: ASP.NET Core 企业级开发架构