csharp / expert
Snippet
Structural Dependency Resolution using Type Mapping
Building a custom dependency resolution engine demonstrates the core mechanics of modern architectural patterns. This implementation uses a functional registry to map interfaces to implementation factories without external dependencies.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
public class MiniContainer{private readonly Dictionary<Type, Func<object>> _registry = new();public void Register<T>(Func<T> factory) => _registry[typeof(T)] = () => factory()!;public T Resolve<T>() => (T)_registry[typeof(T)]();}// Usagevar container = new MiniContainer();container.Register<IDatabase>(() => new SqlDatabase());var db = container.Resolve<IDatabase>();
Breakdown
1
Dictionary<Type, Func<object>>
Stores a mapping of service types to their creation logic.
2
(T)_registry[typeof(T)]()
Invokes the factory and casts the result to the requested type.