.NET Core resolving services from Dependency Injection container
5 March 2022
Instead of injecting N count of service, (for example: Controller’s ctor),
public CustomController(ITestService testService, IAnotherService anotherService, ..... and so another...){
}
Looks boring. Let’s inject IServiceScopeFactory
private readonly IServiceScopeFactory serviceFactory;
public void CustomController(IServiceScopeFactory serviceFactory){
this.serviceFactory= serviceFactory;
}
public void TestServiceMethodExample(){
using var scoped = serviceFactory.CreateScope();
var testService = scoped.ServiceProvider.GetRequiredService<ITestService>();
testService.MethodExample();
}
public void AnotherServiceMethodExample(){
using var scoped = serviceFactory.CreateScope();
var anService = scoped.ServiceProvider.GetRequiredService<IAnotherService>();
anService.AnothetMethodExample();
}
We can resolve every registered service by creating factory scope.