public class XXXContainer : IXXXContainer
{
//ContainerDicationary 保存抽象与细节的映射类型
private Dictionary<string, Type> XXXContainerDicationary = new Dictionary<string, Type>();
public void RegisterType<TFrom, TTo>() where TTo : TFrom
{
XXXContainerDicationary.Add(typeof(TFrom).FullName, typeof(TTo));
}
//实例化对象,无论多少层级
public T Resolve<T>()
{
string abstartName = typeof(T).FullName;
Type type = XXXContainerDicationary[abstartName];
return (T)this.ObjectInstance(type);
}
//递归方法
private object ObjectInstance(Type type)
{
ConstructorInfo ctor = null;
//如果有XXXInjectionConstructor,就找出标记的有XXXInjectionConstructor特性的构造函数
if (type.GetConstructors().Count(c => c.IsDefined(typeof(XXXInjectionConstructor), true)) > 0)
{
ctor = type.GetConstructors().Where(c => c.IsDefined(typeof(XXXInjectionConstructor), true)).OrderByDescending(c => c.GetParameters().Length).FirstOrDefault();
}
else
{
ctor = type.GetConstructors().OrderByDescending(c => c.GetParameters().Length).First();
}
List<object> parameterlist = new List<object>();
foreach (ParameterInfo parameter in ctor.GetParameters())
{
string parameterType = parameter.ParameterType.FullName;
Type targetType = XXXContainerDicationary[parameterType];
object oParameter = this.ObjectInstance(targetType); //隐形的跳出条件:找到最后后一个依赖的五参数构造函数后就不再去递归了;
parameterlist.Add(oParameter);
}
object oInstance = Activator.CreateInstance(type, parameterlist.ToArray());//调用的五参数构造函数;//如果有两级依赖
return oInstance;
}
}
---------------DEMO-----------------------------------------------------------------------------------------
IXXXContainer container = new XXXContainer();//创建一个容器
container.RegisterType<IPhone, ApplePhone>();//告诉容器---抽象和细节的关系
container.RegisterType<IHeadphone, Headphone>();
container.RegisterType<IMicrophone, Microphone>();
container.RegisterType<IPower, Power>();
container.RegisterType<IBaseBll, BaseBll>();
IPhone phone = container.Resolve<IPhone>();//获取对象的实例