在MEF我可以出口通用接口,使用此代碼:如何導出接口與Asp.Net核心依賴注入
registration.ForTypesMatching(t => t.GetInterface(typeof(ICommandHandler<>).Name) != null)
.ExportInterfaces().SetCreationPolicy(CreationPolicy.NonShared);
我怎樣才能在Asp.Net核心配置服務,以實現相同,即註冊服務類只能通過接口?
在MEF我可以出口通用接口,使用此代碼:如何導出接口與Asp.Net核心依賴注入
registration.ForTypesMatching(t => t.GetInterface(typeof(ICommandHandler<>).Name) != null)
.ExportInterfaces().SetCreationPolicy(CreationPolicy.NonShared);
我怎樣才能在Asp.Net核心配置服務,以實現相同,即註冊服務類只能通過接口?
在ASP.NET核心應用程序中,通過擴展Startup.ConfigureServices
方法在Startup.cs
中配置服務。 IServiceCollection實例的services參數允許您添加自己的實現接口的服務。
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// setup of ASP.NET Services like MVC
...
services.AddSingleton<IMyInterface>(objectImplementingMyInterface);
services.AddTransient<IAnotherInterface, SomeAnotherInterfaceImplementer>();
}
如果內置的DI容器(https://docs.asp.net/en/latest/fundamentals/dependency-injection.html)不符合你的要求,那麼有辦法將其他DI容器庫,也基本特徵。一個例子是Autofac(http://docs.autofac.org/en/latest/integration/aspnetcore.html)。 ASP.NET團隊目前正在進行更改,使DI庫維護人員能夠更輕鬆地集成到ASP.NET Core中。
ASP.NET Core提供了由IServiceProvider接口表示的自己的Inversion of Control容器。 有關基本用法以及如何註冊自己的課程,請查看此頁面:https://docs.asp.net/en/latest/fundamentals/dependency-injection.html#。
在ASP.NET Core中集成任何容器總是很容易,如[這裏]所述(https://simpleinjector.org/blog/2016/07/working-around-the-asp-net-core-di-abstraction /)。 – Steven