2016-08-21 105 views
0

在MEF我可以出口通用接口,使用此代码:如何导出接口与Asp.Net核心依赖注入

registration.ForTypesMatching(t => t.GetInterface(typeof(ICommandHandler<>).Name) != null) 
    .ExportInterfaces().SetCreationPolicy(CreationPolicy.NonShared); 

我怎样才能在Asp.Net核心配置服务,以实现相同,即注册服务类只能通过接口?

回答

0

在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中。

+0

在ASP.NET Core中集成任何容器总是很容易,如[这里]所述(https://simpleinjector.org/blog/2016/07/working-around-the-asp-net-core-di-abstraction /)。 – Steven