模拟依赖注入
1、当前代码只模拟了构造函数注入,注入的都是无状态的对象,Son、Father类中的构造方法无形参
namespace HP.DI
{
class Program
{
static void Main(string[] args)
{
MyContainerService.Registerer<ISon, Son>();
MyContainerService.Registerer<IFather, Father>();
MyContainerService.Create<MyControl>();
Console.ReadLine();
}
}
public class MyContainerService
{
static Dictionary<string, Type> dic = new Dictionary<string, Type>();
public static void Registerer<T, T1>() where T1 : T
{
dic.Add(typeof(T).FullName, typeof(T1));
}
public static object Create<T>()
{
Type typeSource = typeof(T);
//获取第一个构造方法 默认类中只有一个构造方法
var ct = typeSource.GetConstructors()[0];
List<object> list = new List<object>();
//循环构造方法 获取构造方法中的接口形参
foreach (var item in ct.GetParameters())
{
//查找到继承类进行实例化,然后加入到list集合
list.Add(Activator.CreateInstance(dic[item.ParameterType.FullName]));
}
object obj = Activator.CreateInstance(typeSource, list.ToArray());
return obj;
}
}
public class MyControl
{
private IFather _father;
private ISon _son;
public MyControl(IFather father, ISon son)
{
this._father = father;
this._son = son;
}
}
public interface ISon
{
}
public class Son : ISon
{
}
public interface IFather
{
}
public class Father : IFather
{
}
}
2、当前代码只模拟了构造函数注入,注入的都是无状态的对象,而且Son、Father类中的构造方法可以有形参,这个时候就需要用到递归了
namespace HP.DI
{
class Program
{
static void Main(string[] args)
{
MyContainerService.Registerer<ISon, Son>();
MyContainerService.Registerer<IFather, Father>();
MyContainerService.Create(typeof(MyControl));
Console.ReadLine();
}
}
public class MyContainerService
{
static Dictionary<string, Type> dic = new Dictionary<string, Type>();
public static void Registerer<T, T1>() where T1 : T
{
dic.Add(typeof(T).FullName, typeof(T1));
}
public static object Create(Type type)
{
//获取第一个构造方法 默认类中只有一个构造方法
var ct = type.GetConstructors()[0];
List<object> list = new List<object>();
//循环构造方法 获取构造方法中的接口形参
foreach (var item in ct.GetParameters())
{
//递归进行实例化,然后加入到list集合
object ob = Create(dic[item.ParameterType.FullName]);
list.Add(ob);
}
object obj = Activator.CreateInstance(type, list.ToArray());
return obj;
}
}
public class MyControl
{
private IFather _father;
private ISon _son;
public MyControl(ISon son, IFather father)
{
this._son = son;
this._father = father;
}
}
public interface ISon
{
}
public class Son : ISon
{
private IFather _father;
public Son(IFather father)
{
this._father = father;
}
}
public interface IFather
{
}
public class Father : IFather
{
}
}