concept lifestyle in category .net

appears as: lifestyles, lifestyle, lifestyle, The lifestyles
Dependency Injection in .NET

This is an excerpt from Manning's book Dependency Injection in .NET.

Lifestyle Comparison Chart

Lifestyle Castle Windsor Structure-Map Spring .NET Autofac Unity MEF
SINGLETON X X X X X X
TRANSIENT X X X X X X
PER GRAPH   X     X  
WEB REQUEST CONTEXT X X (X)   (X)  
Thread Context X X     X  
Session Context   X (X)      
POOLED X          
Scoped       X X  
Custom X X     X  
(X) = partial support

You want ContractMapper to have the SINGLETON lifestyle, so you define this by invoking the SingleInstance method. When it comes to the SqlProductRepository, things become a little more difficult because the SqlProductRepository instance should be TRANSIENT, but the injected connection string should be a SINGLETON. You can achieve this by extracting the connectionString from the application configuration (not shown, but similar to before) and using this outer variable from within the closure you use to specify the constructor. Because connectionString is an outer variable, it remains the same across many invocations of the constructor. Notice how you implicitly scope both SqlProductRepository and ProductManagementService as TRANSIENTS by not specifying a lifestyle.

Although this example describes how to specify lifestyles with Autofac, other DI CONTAINERS have vaguely similar APIs for the same purpose.

The ability to fine-tune each DEPENDENCY’s lifestyle is important for performance reasons but can also be important for functionality. For instance, the Mediator[5] design pattern relies on a shared director through which several components communicate. This only works when the Mediator is shared among the involved collaborators.