ioc&di

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.Collections.Generic;
using System.Linq;

public interface IContainer
{
    void Register<TService, TImplementation>() where TImplementation : TService;
    void Register<TService>(Func<TService> instanceCreator);
    TService Resolve<TService>();
}

public class Container : IContainer
{
    private Dictionary<Type, Func<object>> _registry = new Dictionary<Type, Func<object>>();

    public void Register<TService, TImplementation>() where TImplementation : TService
    {
        _registry[typeof(TService)] = () => Activator.CreateInstance(typeof(TImplementation));
    }

    public void Register<TService>(Func<TService> instanceCreator)
    {
        _registry[typeof(TService)] = () => instanceCreator();
    }

    public TService Resolve<TService>()
    {
        Func<object> creator;
        if (_registry.TryGetValue(typeof(TService), out creator))
        {
            return (TService)creator();
        }
        else
        {
            throw new Exception($"No registration for {typeof(TService)}");
        }
    }
}