C#简单实现IOC容器的示例代码

  using System;

  using System.Collections.Generic;

  public interface IService

  {

  void Execute();

  }

  public class ServiceA : IService

  {

  public void Execute()

  {

  Console.WriteLine("ServiceA is executing.");

  }

  }

  public class ServiceB : IService

  {

  public void Execute()

  {

  Console.WriteLine("ServiceB is executing.");

  }

  }

  public class IoCContainer

  {

  private readonly Dictionary _services = new Dictionary();

  public void Register()

  {

  _services[typeof(TInterface)] = typeof(TImplementation);

  }

  public TInterface Resolve()

  {

  Type implementationType = _services[typeof(TInterface)];

  return (TInterface)Activator.CreateInstance(implementationType);

  }

  }

  class Program

  {

  static void Main(string[] args)

  {

  // 创建 IoC 容器

  IoCContainer container = new IoCContainer();

  // 注册服务

  container.Register();

  container.Register();

  // 解析并使用服务

  IService serviceA = container.Resolve();

  serviceA.Execute(); // 输出:ServiceA is executing.

  IService serviceB = container.Resolve();

  serviceB.Execute(); // 输出:ServiceB is executing.

  }

  }