"From injection to design"
Lightweight IoC container that strives to motivate its users to design their code well instead of offering a quantity of features that could hide design flaws.
Use the nuget package to install Essence IoC with fluent registration.
class MyApplication : IDisposable
{
private readonly Essence.Ioc.Container _container;
public MyApplication()
{
_container = new Essence.Ioc.Container(r =>
{
r.RegisterService<IMyDependency>().ImplementedBy<MyDependencyImplementation>();
r.RegisterService<IMyService>().ImplementedBy<MyServiceImplementation>();
});
}
public void ExecuteMyUseCase()
{
using (_container.Resolve<IMyService>(out var myService))
{
myService.Use();
}
}
public void Dispose()
{
_container.Dispose();
}
}
Only constructor injection is supported.
class MyServiceImplementation : IMyService
{
private readonly IMyDependency _myDependency;
public MyServiceImplementation(IMyDependency myDependency)
{
_myDependency = myDependency;
}
public void Use()
{
_myDependency.Use();
}
}
When registering a service, dependencies of its implementation must be already registered. That means registrations must be ordered from independent services to the ones that have more and more dependencies.
new Essence.Ioc.Container(r =>
{
r.RegisterService<IElectricity>().ImplementedBy<Electricity>();
r.RegisterService<IDoor>().ImplementedBy<ElectricDoor>(); // depends on IElectricity
r.RegisterService<IWater>().ImplementedBy<Water>();
r.RegisterService<IWashDevice>().ImplementedBy<RotatingBrushes>(); // depends on IElectricity and IWater
r.RegisterService<ICarWash>().ImplementedBy<CarWash>(); // depends on IDoor and IWashDevice
})
Not only an instance of the dependency but also a lazy instance and an instance factory delegate can be injected.
class MyServiceImplementation : IService
{
public MyServiceImplementation(
IMyDependency dependency,
Lazy<IMyDependency> lazyDependency,
Func<IMyDependency> dependencyFactory)
{
}
}
IDisposable
service implementations are disposed by the container at the end of their life scope, taking their life style and injection context into account.
Service interfaces must not be IDisposable
as life cycle should be an implementation detail and should be managed by the container.
See unit tests to find more examples and details about Essence IoC features.
- Life cycle management of disposable service implementations.
- Adhering to semantic versioning from now on.
- Resolved instance is returned via out parameter of
Resolve()
method. The method returns anIDisposable
to be able to end the transient life scope. - The container implements
IDisposable
to be able to end the singleton life scope. - Registering after container is constructed fails fast.