DiLite /dɪˈlʌɪt/ is a minimalist, lightweight DI framework. Registrations and resolutions will look very familiar to those accustomed to Autofac.
Create a ContainerBuilder
, make the registrations, then build your Container
:
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<MyClass>().As<IMyClass>();
var container = containerBuilder.Build();
Then simply resolve what you need from the Container
:
var myInstance = container.Resolve<IMyClass>();
Each resolution call to the container will create a new instance of the registered type, unless it is specified as a singleton during registration. To register a type as a singleton, just use the AsSingleInstance
method:
containerBuilder.RegisterType<MyClass>().As<IMyClass>().AsSingleInstance();
If no alias is specified during the registration of a type, it will be registered as itself.
containerBuilder.RegisterType<MyClass>();
It can be resolved as:
var myInstance = container.Resolve<MyClass>();
If another alias is specified, but the registration as itself is also needed, the AsSelf
method must be used:
containerBuilder.RegisterType<MyClass>().As<IMyClass>().AsSelf();
Multiple registrations can be made for the same alias:
containerBuilder.RegisterType<MyClassImplementation1>().As<IMyClass>();
containerBuilder.RegisterType<MyClassImplementation2>().As<IMyClass>();
In this case, the Resolve
method will return an instance of MyClassImplementation2
because it was the last one registered for that alias. By using the ResolveAll
method, all registrations for the alias will be returned:
IEnumerable<IMyClass> myInstances = container.ResolveAll<IMyClass>();
Factory methods can also be registered as Func<IContainer, T>
:
containerBuilder.RegisterFactoryMethod(container =>
{
var dep1 = container.Resolve<IDependency1>();
var dep2 = container.Resolve<IDependency2>();
return new MyClass(dep1, dep2);
}).As<IMyClass>();
These registrations can be resolved as their simple type counterparts:
var myInstance = container.Resolve<IMyClass>();