简体   繁体   English

.Net Core + DI: Class 集中接口

[英].Net Core + DI: Class To Centralize Interfaces

I am new on.Net Core and Microsoft Dependency Injection and what I am trying to do is something similar to '.ToFactory()' (from ninject) which I can create a class containing all my interfaces services, avoiding a lot of IMyClassService on my controllers.我是.Net Core 和Microsoft Dependency Injection 的新手,我想做的是类似于'.ToFactory()'(来自ninject),我可以创建一个包含我所有接口服务的class,避免很多IMyClassService我的控制器。 In.Net Framework + Ninject I used to do: In.Net Framework + Ninject 我曾经做过:

NinjectModule忍者模块

Bind< IAppServiceFactory >().ToFactory();

IAppServiceFactory class IAppServiceFactory class

public interface IAppServiceFactory
{
    IAccessAgreementAppService AccessAgreement { get; }
    IAccessAgreementUserAppService AccessAgreementUser { get; }
    ...

Controllers控制器

private readonly IMapper _mapper;
private readonly IAppServiceFactory _appServiceFactory;

public MyController(IMapper mapper,
    IAppServiceFactory appServiceFactory)
{
    _mapper = mapper;
    _appServiceFactory = appServiceFactory;
}

public ActionResult Index()
{
    var all = _appServiceFactory.AccessAgreementUser.GetAll();
}

The main reason is having a cleaner controller, instead of主要原因是有一个更清洁的 controller,而不是

private readonly IAccessAgreementAppService _accessAgreementAppService;
private readonly IAccessAgreementUserAppService _accessAgreementUserAppService;
...
public MyController(IAccessAgreementAppService accessAgreementAppService,
    IAccessAgreementUserAppService accessAgreementUserAppService,
    ...

You can request IServiceProvider and get the service yourself.您可以请求IServiceProvider并自己获取服务。

 public MyController(IServiceProvider serviceProvider)
 {
         using (var scope = serviceProvider.CreateScope())
         {
             var service = scope.ServiceProvider.GetRequiredService<IAccessAgreementAppService();
             var all = service.GetAll();    
         }
 }

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

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