Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control the scope of Dependency Injection in .Net Core 2

We are developing a class library in .Net 2.0 Core. We use dependency injection straight out of the box. We have some services that we want to resolve from the container as "Scoped".

How can we start (and end) such Scope in code. It would be nice to be able to do this during some of our more elaborate test scenarios.

Note: we do not use "ASP.Net Core"

like image 561
k.c. Avatar asked Nov 06 '25 02:11

k.c.


1 Answers

using Microsoft.Extensions.DependencyInjection; // it's an extension method



using (var scope = serviceProvider.CreateScope())
{
   // in your new Scope, use the scope's ServiceProvider
   var service = scope.ServiceProvider.GetService<SomeService>();

}
like image 78
Henk Holterman Avatar answered Nov 08 '25 19:11

Henk Holterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!