ASP.NET Core DI 通常使用構造函數注入獲取對象,好比在ConfigureServices
配置注入後,經過下面方式獲取:app
private IValueService _valueService; public ValueController(IValueService valueService) { _valueService = valueService; }
那若是手動獲取注入對象呢?dom
第一種獲取方式(有時會獲取不到,不推薦使用):ide
var services = new ServiceCollection(); var provider = services.BuildServiceProvider(); var _valueService = provider.GetService<IValueService>();
第二種獲取方式(推薦使用):函數
public void Configure(IApplicationBuilder app) { ServiceLocator.Instance = app.ApplicationServices; } public static class ServiceLocator { public static IServiceProvider Instance { get; set; } } public void SomeRandomMethod() { var valueService = ServiceLocator.Instance.GetService<IValueService>(); // Do something with service }
補充:須要注意的是,使用ServiceLocator.Instance.GetService<T>();
,只能獲取AddTransient
和AddSingleton
注入的對象,而不能獲取AddScoped
(請求生命週期內惟一)注入的對象,不是不能獲取,而是獲取的和構造函數獲取的不是相同對象,也就是說獲取的對象沒有共享,使用場景好比IUnitOfWork
。ui
那怎麼手動獲取請求生命週期內的注入對象呢?方法以下:spa
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace Sample.Domain { public class SampleDomainService : IDomainService { private IUnitOfWork _unitOfWork; public SampleDomainService(IHttpContextAccessor httpContextAccessor) { _unitOfWork = httpContextAccessor.HttpContext.RequestServices.GetService<IUnitOfWork>(); } } }
IHttpContextAccessor
接口在Microsoft.AspNetCore.Http.Abstractions
Nuget 程序包下。code