Lifestyles
The MicroKernel supports the concept of lifestyles which basically controls how many instances a component will have. MicroKernel comes with support for the following lifestyles:
- Singleton (the default) There will be only one instance of the component. When requested, clients will always receive that instance.
- Transient For each request the container will create a new instance
- PerThread A singleton per thread.
- Pooled Instances will be pooled to avoid unnecessary constructions.
- Custom Your own homegrown lifestyle
You can associate the desired lifestyle for your components in two ways: by using an attribute or through the configuration. For example, the following two are equivalent:
[Transient] public class MyComponent { // ... }
<component id="mycomponent" lifestyle="transient" />
Please note that if you use both, the configuration overrides whatever is defined on the class.
Aside from the TransientAttribute you can also use PerThread, Pooled, Singleton and Custom. To use Custom, you need to supply an associated type that will be responsible for the lifestyle of your component:
[CustomLifestyle( typeof(MyLifestyleManager) )] public class MyComponent { ... }
Which can be expressed in configuration by supplying the lifestyle attribute set to custom and the customLifestyleType attribute set to the Type of your LifeStyleManager:
<component id="my.component" type="MyLib.MyComponent, MyLib" lifestyle="custom" customLifestyleType="MyLib.MyCustomLifestyle, MyLib" />
To create your own LifeStyleManager, your class must implement the interface ILifestyleManager. For example, you could create a LifeStyleManager that creates a singleton object per web-request like this:
public class PerWebRequestLifestyleManager : AbstractLifestyleManager { private string PerRequestObjectID = "PerRequestLifestyleManager_" + Guid.NewGuid().ToString(); public override object Resolve() { if(HttpContext.Current.Items[PerRequestObjectID] == null) { // Create the actual object HttpContext.Current.Items[PerRequestObjectID] = base.Resolve(); } return HttpContext.Current.Items[PerRequestObjectID]; } public override void Dispose() { } }