简体   繁体   中英

.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. In.Net Framework + Ninject I used to do:

NinjectModule

Bind< IAppServiceFactory >().ToFactory();

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

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

You can request IServiceProvider and get the service yourself.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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