Registration Concepts¶
Interface IContainerBuilder represents a few overloadings of the method Register()
, designed to register IoC-container components. Registration
methods also define the way of creating instances of components. Instances components may be made via reflection by means IoC-container itself;
may be represented by beforehand created instance; may be created by a factory function or a lambda-expression. Each component may represent one or
a few services defined with using one of the methods As().
public interface IMyService
{
// ...
}
public class MyComponent : IMyService
{
// ...
}
public class ContainerModule : IContainerModule
{
public void Load(IContainerBuilder builder)
{
builder.RegisterType<MyComponent>().As<IMyService>();
// ...
}
}
Register Types¶
Component instances registered with method RegisterType() created by reflection and class constructor with the most number of parameters retrievable from container.
// Способ 1
builder.RegisterType<MyComponent>().As<IMyService>();
// Способ 2
builder.RegisterType(typeof(MyComponent)).As(typeof(IMyService));
Register Generic Types¶
If component presented as generic-type to register one should use method RegisterGeneric(). As in case of regular types, instances of generic-components created by reflection and class constructor with the most number of parameters retrievable from container.
public interface IRepository<T> { /* ... */ }
public class MyRepository<T> : IRepository<T> { /* ... */ }
// ...
builder.RegisterGeneric(typeof(MyRepository<>)).As(typeof(IRepository<>));
Register Instances¶
In some cases you may want to register an instance component created beforehand. For example, if creation of the component requires a lot of resources or is a technically complicated task. To register such components one should use method RegisterInstance().
builder.RegisterInstance(new MyComponent()).As<IMyService>();
Register Factory Functions¶
Component may be registered by a factory function or lambda-expression. This way suits well when creation of component instance should be accompanied by preliminary calculations or is impossible to be created by class constructor. Such components should be registered via method RegisterFactory().
builder.RegisterFactory(r => new MyComponent()).As<IMyService>();
Input parameter r
represents context of IoC-container, which can be used to get all dependencies required to create
component. This approach is the most fitting rather than obtaining dependencies via closure because this ensures a unified way of managing the life
cycle of all dependencies.
builder.RegisterFactory(r => new A(r.Resolve<B>()));