0 day streak
csharp / expert
Snippet

Minimalistic Dependency Injection Container

Understanding the internals of frameworks is vital for expert developers. This snippet implements a basic IoC (Inversion of Control) container using a dictionary of factory delegates. It demonstrates how types are mapped to instantiation logic without relying on heavy external libraries.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class SimpleContainer
{
private readonly Dictionary<Type, Func<object>> _factories = new();
public void Register<T>(Func<T> factory) where T : class
=> _factories[typeof(T)] = () => factory();
public T Resolve<T>() where T : class
=> (T)_factories[typeof(T)]();
}
// Usage
var container = new SimpleContainer();
container.Register<ILogger>(() => new ConsoleLogger());
var logger = container.Resolve<ILogger>();
Breakdown
1
Dictionary<Type, Func<object>>
Stores a mapping from an interface or class type to a function that creates its instance.
2
Register<T>(Func<T> factory)
Saves a lambda expression that will be invoked whenever the type T is requested.