Create a Container
and register your dependencies with AddSingleton
, AddScoped
and AddTransient
methods.
Resolve your dependencies with Resolve
method.
To use this library in Autodesk Revit, use the ricaun.Revit.DI library.
This project uses the same implementation from Onbox IOC container system, except by:
The Container
when Dispose
can dispose all IDisposable
scoped instances registered in the container.
// Empty Container.
Container container = new Container();
// Dispose Container.
container.Dispose();
// Create Container with itself registered as a singleton.
IContainer container = ContainerUtils.CreateContainer();
// Create Container with itself registered as a singleton, with dispose scoped instances enabled.
IContainer container = ContainerUtils.CreateContainer(true);
// Register a singleton.
var singleton = new Singleton();
container.AddSingleton(singleton);
container.AddSingleton<ISingleton>(singleton);
container.AddSingleton<ISingleton, Singleton>();
container.AddSingleton<ISingleton, Singleton>(singleton);
// Register a scoped.
container.AddScoped<Scoped>();
container.AddScoped<IScoped, Scoped>();
// Register a transient.
container.AddTransient<Transient>();
container.AddTransient<ITransient, Transient>();
// Resolve the ISingleton.
var singleton = container.Resolve<ISingleton>();
// Resolve the IScoped.
var scoped = container.Resolve<IScoped>();
// Resolve the ITransient.
var transient = container.Resolve<ITransient>();
// Resolve the ISingleton.
var singleton = container.ResolveOrNull<ISingleton>();
// Resolve the IScoped.
var scoped = container.ResolveOrNull<IScoped>();
// Resolve the ITransient.
var transient = container.ResolveOrNull<ITransient>();
// Enable Console.
container.EnableConsolePrinting(true);
// Enable Dispose Scoped Instances.
container.EnableDisposeScopedInstances(true);
Simple Host
static class to hold the container.
using ricaun.DI;
public static class Host
{
public static IContainer Container { get; } = ContainerUtils.CreateContainer();
public static IContainerResolver ContainerResolver => Container;
public static T Resolve<T>() where T : class => ContainerResolver.Resolve<T>();
public static T ResolveOrNull<T>() where T : class => ContainerResolver.ResolveOrNull<T>();
}
Extension for the IHost
interface.
public interface IHost { }
public static class HostExtension
{
public static IContainer GetContainer(this IHost _) => Host.Container;
public static IContainerResolver GetContainerResolver(this IHost _) => Host.ContainerResolver;
public static T Resolve<T>(this IHost _) where T : class => Host.Resolve<T>();
public static T ResolveOrNull<T>(this IHost _) where T : class => Host.ResolveOrNull<T>();
}
This project is licensed under the MIT Licence.
Do you like this project? Please star this project on GitHub!