csharp / expert
Snippet
Minimalist Inversion of Control Container Architecture
Implementing a basic Inversion of Control (IoC) container from scratch demonstrates the 'frameworks' concept using only core language features. This pattern uses delegates and type-mapping to decouple object creation from its consumption, adhering to the Dependency Inversion Principle without relying on external libraries.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;using System.Collections.Generic;public class CoreContainer{private readonly Dictionary<Type, Func<object>> _registry = new();public void Bind<T>(Func<T> factory) => _registry[typeof(T)] = () => factory()!;public T Get<T>() => (T)_registry[typeof(T)]();}// Usage:var container = new CoreContainer();container.Bind<IDatabase>(() => new SqlDatabase());var db = container.Get<IDatabase>();
Breakdown
1
private readonly Dictionary<Type, Func<object>> _registry = new();
Stores a mapping of types to factory functions for instantiation.
2
public T Get<T>() => (T)_registry[typeof(T)]();
Retrieves the factory and executes it, casting the result to the desired type.