LifestyleCreateHybrid Method (FuncBoolean, Lifestyle, Lifestyle)

Simple Injector
The hybrid lifestyle allows mixing two lifestyles in a single registration. Based on the supplied lifestyleSelector delegate the hybrid lifestyle will redirect the creation of the instance to the correct lifestyle. The result of the lifestyleSelector delegate will not be cached; it is invoked each time an instance is requested or injected. By nesting hybrid lifestyles, any number of lifestyles can be mixed.

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

public static Lifestyle CreateHybrid(
	Func<bool> lifestyleSelector,
	Lifestyle trueLifestyle,
	Lifestyle falseLifestyle
)

Parameters

lifestyleSelector
Type: SystemFuncBoolean
The FuncTResult delegate that determines which lifestyle should be used. The trueLifestyle will be used if true is returned; the falseLifestyle otherwise. This delegate will be called every time an instance needs to be resolved or injected.
trueLifestyle
Type: SimpleInjectorLifestyle
The lifestyle to use when lifestyleSelector returns true.
falseLifestyle
Type: SimpleInjectorLifestyle
The lifestyle to use when lifestyleSelector returns false.

Return Value

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

ExceptionCondition
ArgumentNullExceptionThrown when one of the supplied arguments is a null reference.
Examples

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

C#
// NOTE: WebRequestLifestyle is located in SimpleInjector.Integration.Web.dll.
var mixedScopeLifestyle = Lifestyle.CreateHybrid(
    () => HttpContext.Current != null,
    new WebRequestLifestyle(),
    new ThreadScopedLifestyle());

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

Hybrid lifestyles can be nested:

C#
var lifestyle = new ThreadScopedLifestyle();
var mixedLifetimeTransientLifestyle = Lifestyle.CreateHybrid(
    () => lifestyle.GetCurrentScope(container) != null,
    lifestyle,
    Lifestyle.Transient);

var mixedScopeLifestyle = Lifestyle.CreateHybrid(
    () => HttpContext.Current != null,
    new WebRequestLifestyle(),
    mixedLifetimeTransientLifestyle);

The mixedScopeLifestyle now mixed three lifestyles: Web Request, Lifetime Scope and Transient.

See Also

Reference