Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between creating a scope using Autofac LifeTimeScope and Asp.net Core DI Extension IServiceScopeFactory

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.

like image 943
Lucas Casagrande Avatar asked Aug 01 '17 19:08

Lucas Casagrande


1 Answers

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.

like image 177
Travis Illig Avatar answered Sep 28 '22 03:09

Travis Illig