.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,
    ...

Upvotes: 0

Views: 156

Answers (1)

jeb
jeb

Reputation: 1316

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();    
         }
 }

Upvotes: 1

Related Questions