I'm developing an application in Asp.net Core using the Autofac as the default DI and in my integration tests I require some services which before installing
the Autofac I was injecting by creating a IServiceScopeFactory
and then calling the method CreateScope()
to be able to get the services needed, just like the code below:
public void ExampleOfAspNetServiceScope(){
var scopeFactory = _testServer.Host.Services.GetRequiredService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope()){
var service = scope.ServiceProvider.GetService<ISomeService>();
// Some stuff...
}
}
After installing the Autofac into my application I've found in the documentation the interface ILifeTimeScope and now my code could be rewriten as follows:
public void ExampleOfAutofacScope(){
var lifetimeScope = _testServer.Host.Services.GetRequiredService<ILifetimeScope>();
using (var scope = lifetimeScope.BeginLifetimeScope()){
var service = scope.Resolve<ISomeService>();
// Some stuff...
}
}
I did integration tests with both and it seems they behave equally. So, I was wondering what are the differences between the two approaches.
Thanks in advance.
It's the same thing, just using the Microsoft.Extensions.DependencyInjection abstractions instead of using Autofac directly.
I'd recommend looking at the actual code in Autofac.Extensions.DependencyInjection for more concrete clarity. There's not actually much to it and you can see for yourself precisely how it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With