Skip to content

Lifestyles

Simon Gockner edited this page Oct 15, 2019 · 9 revisions

There are multiple lifestyles available. These are needed for the registration of your classes. Depending on their lifestyle it is decided which instance is returned once you resolve it.

The following documentation is supposed to help you decide, which Lifestyle you want to use for your need.
The lifestyles are part of the enum Lifestyle.

Lifestyle.Transient

Using the Transient-Lifestyle, a new instance gets created every time an instance is resolved.
Transient instances are not tracked by the IocContainer, so once you don't need them anymore they can be claimed by the garbage collector without leaking memory.

ℹ️ This is the default Lifestyle that the IocContainer uses.

This is how you register a class as Transient:

container.Register<IFoo, Foo>());

Lifestyle.Singleton

The Singleton-Lifestyle is used to always get the same instance every time an instance is resolved.
Singleton instances will be created the first time they are requested and then reused whenever they are needed. They are bound to the IocContainer and will only be released once the IocContainer is disposed.
This is specifically useful if you have a service that needs to be accessed by multiple components of your application.

This is how you register a class as Singleton:

container.Register<IFoo, Foo>(Lifestyle.Singleton);

Lifestyle.Multiton

When using the Multiton-Lifestyle, a new instance gets created if the given scope has no created instance yet. Otherwise the already created instance is used.
Multiton instances will be created the first time they are requested for a given scope and then reused whenever requested for their scope.
They are also bound to the IocContainer but different to singletons, they can be cleared when you need to do so by calling:

IocContainer.ClearMultitonInstances<T>()  

They will also be released once the IocContainer is disposed.

This is how you register a class as Multiton:

container.Register<IFoo, Foo, TScope>();