通过类型反射实现简单Ioc功能

任务目标

最小化目标实现Ioc基本的 组件注册Registor和组件使用Resolve功能

环境

C#

用到的知识点

  1. C# 反射基础
  2. C# 泛型基础

结构内容

  1. TypeFactory 类型Ioc 容器-控制器
public static class TypeFactory
{
	//静态类字典 key-要注册的接口 value-要注册的目标类
	private static readonly Dictionary<Type, Type> _dic = new Dictionary<Type, Type>();
        //输出函数     TInterface是之前注册的类型接口
	public static TInterface Resolve<TInterface>() where TInterface:IRegistor
	{
		if (!_dic.ContainsKey(typeof(TInterface)))
		{
			throw new Exception("not contain this interface");
		}
		Type dest = _dic[typeof(TInterface)];
		var obj=dest.Assembly.CreateInstance(dest.FullName);
		return (TInterface)obj;
	}
        //注册函数 TClass是要注册的类 TInterface是要注册的接口   
	public static void Register<TClass, TInterface>() where TInterface:IRegistor where TClass:TInterface
	{
		if (_dic.ContainsKey(typeof(TInterface)))
		{
			_dic[typeof(TInterface)] = typeof(TClass);
		}
		else
		{
			_dic.Add(typeof(TInterface), typeof(TClass));
		}
	}
}
  1. 用到的类和接口
//注册根接口 限制泛型
public interface IRegistor
{
}
//范例接口    
public interface IDBService: IRegistor
{
	public void Run();
}
//返利类
public class DBService:IDBService
{
	public void Run()
	{
		Console.WriteLine("DBService.Run");
	}
}
  1. 使用
class Program
{
	static void Main(string[] args)
	{
		//注册类型和接口
		TypeFactory.Register<DBService, IDBService>();
		//调用Ioc获取应用
		var service = TypeFactory.Resolve<IDBService>();
		//接口执行
		service.Run();
		Console.WriteLine("Done");
		Console.ReadKey();
	}
}

总结

基本的Ioc功能已经实现

原文地址:https://www.cnblogs.com/omiprise/p/13913003.html