LifestyleCreateHybrid Method (ScopedLifestyle, ScopedLifestyle)

Simple Injector
The hybrid lifestyle allows mixing two lifestyles in a single registration. The hybrid will use the defaultLifestyle in case its GetCurrentScope method returns a scope; otherwise the fallbackLifestyle is used. The hybrid lifestyle will redirect the creation of the instance to the selected lifestyle. By nesting hybrid lifestyles, any number of lifestyles can be mixed.

Namespace:  SimpleInjector
Assembly:  SimpleInjector (in SimpleInjector.dll) Version: 4.0.0
Syntax

public static ScopedLifestyle CreateHybrid(
	ScopedLifestyle defaultLifestyle,
	ScopedLifestyle fallbackLifestyle
)

Parameters

defaultLifestyle
Type: SimpleInjectorScopedLifestyle
The lifestyle to use when its GetCurrentScope method returns a scope..
fallbackLifestyle
Type: SimpleInjectorScopedLifestyle
The lifestyle to use when the GetCurrentScope method of the defaultLifestyle argument returns null.

Return Value

Type: ScopedLifestyle
A new hybrid lifestyle that wraps the supplied lifestyles.
Exceptions

ExceptionCondition
ArgumentNullExceptionThrown when one of the supplied arguments is a null reference (Nothing in VB).
Examples

The following example shows the creation of a HybridLifestyle that mixes an ThreadScopedLifestyle and Transient:

C#
// NOTE: WebRequestLifestyle is located in SimpleInjector.Integration.Web.dll.
ScopedLifestyle hybridLifestyle = Lifestyle.CreateHybrid(
    defaultLifestyle: new ThreadScopedLifestyle(),
    fallbackLifestyle: new WebRequestLifestyle());

// The created lifestyle can be reused for many registrations.
container.Register<IUserRepository, SqlUserRepository>(hybridLifestyle);
container.Register<ICustomerRepository, SqlCustomerRepository>(hybridLifestyle);

Hybrid lifestyles can be nested:

C#
ScopedLifestyle hybridLifestyle = Lifestyle.CreateHybrid(
    defaultLifestyle: new ThreadScopedLifestyle(),
    fallbackLifestyle: new WebRequestLifestyle());

var hybridLifestyle = Lifestyle.CreateHybrid(hybridLifestyle, Lifestyle.Transient);

The mixedScopeLifestyle now mixed three lifestyles: Web Request, Thread Scoped and Transient.

See Also

Reference