Diwire is a lightweight IoC container for Microsoft .NET. It provides Dependency injection without reflection and is therefore unlikely many other IoC containers.
This project was created to play around with dependency injection and the Roslyn .NET compiler features (analyzer & code fix provider).
- Lightweight IoC Container
- Supports Singleton and Transient lifetime scope
- Only a single constructor (public or internal) is supported
- No advanced IoC features like interceptors
- Do some performance measurements
- Using the newly announced C# Source Generators instead of CodeFixProvider
- Adding unit tests for the analyzer & code fix provider
- Support for custom lifetime scopes
Install the latest Diwire nuget package.
var container = new DiwireContainer();
// Register the Clock class for the IClock interface as a singleton.
// The factory method (lambda) will be invoked only once when the first insance of an IClock interface is requested.
container.RegisterSingleton<IClock>(_ => new Clock());
// Register a type with a transient lifetime. The factory method (lambda) will be invoked everty time, the type is resolved.
// The factory method can use the provided IContainerProvider (x) to resolve further dependencies.
container.RegisterTransient<IFooService>(x => new FooService(x.Resolve<IClock>()));
// Register a class without a mapping to an interface
container.RegisterSingleton(_ => new MyViewModel());
But wait, you definitiy don't want to register all the types by specifying a factory method! Everytime a parameter of the constructor changes, you whould have to update the registration to match the parameters. Here comes the Diwire code fix provider to the rescue. Create a module class that implements IModule and register types by using the RegisterType attribute:
[RegisterType(typeof(IClock), typeof(Clock))]
[RegisterType(typeof(IFooService), typeof(FooService), Diwire.Lifetime.Transient)]
public class MyServicesModule : IModule
{
}
The Diwire code fix provider will suggest to implement the RegisterType methode and generates all the code of the type registration.
[RegisterType(typeof(IClock), typeof(Clock))]
[RegisterType(typeof(IFooService), typeof(FooService), Diwire.Lifetime.Transient)]
public class MyServicesModule : IModule
{
public void RegisterTypes(Diwire.Abstraction.IContainerRegistry containerRegistry)
{
// This Code was generated by Diwire;
containerRegistry.RegisterSingleton<DiwireSample.MyServices.IClock>(_ => new DiwireSample.MyServices.Clock());
containerRegistry.RegisterTransient<DiwireSample.MyServices.IFooService>(_ => new DiwireSample.MyServices.FooService(_.Resolve<DiwireSample.MyServices.IClock>()));
}
}
var container = new DiwireContainer();
var fooService = container.Resolve<IFooService>();