Skip to content

Registration lifetimes

Kyle Ondy edited this page May 9, 2017 · 12 revisions

Registration / Lifetimes

Registration API

TinyIoC supports registration of concrete types, or registration of concrete implementations of interfaces/base classes:

container.Register<MyConcreteType>();
container.Register<IMyInterface, MyImplementation>();

TinyIoC supports named and unnamed registrations:

container.Register<MyConcreteType>(); // Unnamed
container.Register<MyConcreteType>("Name"); // Name

You can also specify a factory delegate, or an already constructed instance:

// Specifying a factory delegate
container.Register<MyConcreteType>((c,p) => MyConcreteType.GetNew());

// Specifying an already constructed instance
var instance = MyConcreteType.GetNew();
container.Register<IMyInterface, MyConcreteType>(instance); 

By default TinyIoC uses the "greediest" constructor it can satisfy (i.e. the one with the most parameters), but this behavior can be overridden to a specific constructor during registration:

// This example forces this overload:
// public MyConcreteType(IMyInterface dependency, int property1, string property2)
container.Register<MyConcreteType>().UsingConstructor(() => new MyConcreteType(null as IMyInterface, 1, ""));

Multiple implementations of the same baseclass/interface can be registered using RegisterMultiple. This can be useful if you have a marker interface/shared base class and you want to register multiple implementations to retrieve later using ResolveAll or using an IEnumerable dependency:

container.RegisterMultiple<IMyMarkerInterface>(new[] { typeof(MyImplementationClass1), typeof(MyImplementationClass2) });

Lifetimes

By default TinyIoC will register concrete classes as multi-instance and interface registrations as singletons. This behavior can be overriden using the fluent API:

// By default we register concrete types as 
// multi-instance, and interfaces as singletons
container.Register<MyConcreteType>(); // Multi-instance
container.Register<IMyInterface, MyConcreteType>(); // Singleton 

// Fluent API allows us to change that behaviour
container.Register<MyConcreteType>().AsSingleton(); // Singleton
container.Register<IMyInterface, MyConcreteType>().AsMultiInstance(); // Multi-instance 

If running on ASP.Net you can include TinyIoCAspNetExtensions.cs to get access to per-request lifetime. This is set using the same fluent API as above:

container.Register<MyConcreteType>().AsPerRequestSingleton();
container.Register<MyInterface, MyImplementation>().AsPerRequestSingleton();

Note that here the singleton suffix does not mean a global application lifetime singleton so don't confuse it with AsSingleton(). In this context, singleton means that instances registered this way will have a lifetime as a singleton only during a request and they will be destroyed after that.