繁体   English   中英

asp.net core 2.0 DI 将多个 IInterface 类注入控制器

[英]asp.net core 2.0 DI Injecting multiple classes of IInterface into a controller

我将创建数百个类。 如果都实现了同一个类,是不是要一一注册?

例子

public class Service<TEntity>: IService<TEntity> {...}

public Interface IService<TEntity> where TEntity : class {...}

public class class1 : Service<apple>, IClass1 {...}

public class class234 : Service<orange>, IClass234 {...}

在我的控制器中,我想像这样注入它

public class FoodController : Controller{
     private IClass1 _class1;
     private IClass234 _class234;

     FoodController(IClass1 ic1, IClass234 ic234){
          _class1 = ic1;
          _class234 = ic234;
     }
}

我之前在旧版本的ASP.NET使用 Unity 完成了此操作,如何使用ASP.NET CORE 2.0的内置 DI 执行此操作?

在控制器中,我可以在构造函数中注入IClass1IClass234的具体接口。 这就是我想要实现的目标,因为我还想使用类实现的其他接口中的其他方法。

public void ConfigureServices(IServiceCollection services)
{
    // Is there a way to register all 234 classes without typing out services.addTransient...
}

使用标准 DI 容器,您必须一一注册。

但是您可以使用另一个库通过命名约定自动注册它:

https://www.google.com/amp/s/andrewlock.net/using-scrutor-to-automatically-register-your-services-with-the-asp-net-core-di-container/amp/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM