在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