IoC和DI

解释一下IoC和DI的概念:

IoC (Inversion of Control) - 控制反转

控制反转是一种软件设计原则,它将传统的程序控制流程颠倒过来:

  • 传统方式:对象自己创建和管理依赖项
  • IoC方式:对象的依赖项由外部容器或框架来创建和注入

DI (Dependency Injection) - 依赖注入

依赖注入是实现IoC的一种具体方式,通过以下方式实现:

  1. 构造函数注入:通过构造函数传入依赖项
  2. 属性注入:通过属性设置依赖项
  3. 方法注入:通过方法参数传入依赖项
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)}");
        }
    }
}