首页 > 其他分享 >IOC--DI--自定义容器

IOC--DI--自定义容器

时间:2022-10-19 22:13:43浏览次数:50  
标签:container XXXInjectionConstructor 自定义 RegisterType -- type typeof IOC

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>();//获取对象的实例

标签:container,XXXInjectionConstructor,自定义,RegisterType,--,type,typeof,IOC
From: https://www.cnblogs.com/csj007523/p/16808028.html

相关文章