Search code examples
c#dependency-injectioninversion-of-controlsimple-injector

How to define DefaultScopedLifestyle in Simple Injector version 3.0.0?


I am working with dependency injection in a project using simple injector, and it works fine untill I needed to define a lifestyle when resolving a dependency in that particular version, 3.0.0(I am using this version because I am using visual studio 2010).

In the official documentation, it says that I can define a lifestyle of a dependency using this line of code:

container.Register<IService, RealService>(Lifestyle.Scoped);

But when I verify it, it tells me that I should define the DefaultScopeLifestyle, using this(or variations):

container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

But in this version, I could not find the AsyncScopedLifestyle class or its variations.

How can I set the DefaultScopeLifestyle, or set it directly in a dependency?


Solution

  • The v3 equivalent of AsyncScopedLifestyle is ExecutionContextScopeLifestyle:

    container.Options.DefaultScopedLifestyle = new ExecutionContextScopeLifestyle();
    

    This lifestyle is located in the SimpleInjector.Extensions.ExecutionContextScoping nuget package.

    This package requires you to run .NET 4.5 or above.

    If you are using .NET 4.0, you will have to use LifetimeScopeLifestyle/ThreadScopedLifestyle and run your operations synchronously or use WebRequestLifestyle in case you are building a web application.

    You can find more information about LifetimeScope here and about ThreadScopedLifestyle here.