There is a Console Application. There are 3 services:
public class SingletonService
{
public SingletonService()
{
Console.WriteLine("SingletonService constructor");
}
}
public class AppScopeService
{
public AppScopeService(SingletonService singletonService)
{
Console.WriteLine("AppScopeService constructor");
}
}
public class InnerScopeService
{
public InnerScopeService(SingletonService singletonService, AppScopeService appScopeService)
{
Console.WriteLine("InnerScopeService constructor");
}
}
I use Simple Injector DI container to create the services:
public class ScopeExperiment
{
public ScopeExperiment()
{
var container = new Container();
container.Options.DefaultScopedLifestyle = ScopedLifestyle.Flowing;
container.Register<SingletonService>(Lifestyle.Singleton);
container.Register<AppScopeService>(Lifestyle.Scoped);
container.Register<InnerScopeService>(Lifestyle.Scoped);
using (var appScope = new Scope(container))
{
Console.WriteLine("<------app scope----->");
var app = appScope.GetInstance<AppScopeService>();
using (var innerScope = new Scope(container))
{
Console.WriteLine("<------inner scope----->");
var innerService = innerScope.GetInstance<InnerScopeService>();
}
using (var innerScope = new Scope(container))
{
Console.WriteLine("<------inner scope 2----->");
var innerService = innerScope.GetInstance<InnerScopeService>();
}
}
}
}
Run: Program>new ScopeExperiment();
Result in console:
<------app scope----->
SingletonService constructor
AppScopeService constructor
InnerScopeService constructor
<------inner scope----->
AppScopeService constructor
InnerScopeService constructor
<------inner scope 2----->
AppScopeService constructor
InnerScopeService constructor
Expected result:
<------app scope----->
SingletonService constructor
AppScopeService constructor
InnerScopeService constructor
<------inner scope----->
InnerScopeService constructor
<------inner scope 2----->
InnerScopeService constructor
"InnerScopeService" injects "AppScopeService" in constructor. The problem is that "AppScopeService" is created every time "InnerScopeService" is created. Desired behavior is to create "AppScopeService" only once per "appScope".
- Is there any way to explain to DI container that I want to get dependency from the outer scope (appScope).
- Does simpleInjector DI container supports nested scopes?
Nested scopes is not a feature that is supported out of the box, but can be implemented, for instance, using the code below.
There are 3 services:
create the services:
Result in console: