标签:derby ons null ring contains orm new lda obj
interface ImContainer { void RegisterType<TForm, TTo>() where TTo : TForm; TForm Resolve<TForm>(); }
class mContainer : ImContainer { private Dictionary<string, Type> keyValuePairs = new Dictionary<string, Type>(); public void RegisterType<TForm, TTo>() where TTo : TForm { keyValuePairs.Add(typeof(TForm).FullName, typeof(TTo)); } public T Resolve<T>() { Type type = keyValuePairs[typeof(T).FullName]; return Resolve<T>(type); } private T Resolve<T>(Type type) { if (keyValuePairs.ContainsKey(type.FullName)) { type = keyValuePairs[type.FullName]; } //构造注入 var ctorArray = type.GetConstructors(); var ctor = ctorArray.FirstOrDefault(x => x.IsDefined(typeof(musAttribute), true)); if (ctor == null) { ctor = ctorArray.OrderBy(x => x.GetParameters().Length).Last(); } List<object> list = new List<object>(); foreach (var item in ctor.GetParameters()) { var itemType = item.ParameterType; var itemTargeType = keyValuePairs[itemType.FullName]; var target = this.Resolve<object>(itemTargeType); list.Add(target); } T t = default(T); t = (T)Activator.CreateInstance(type, list.ToArray()); //属性注入 var protes = type.GetProperties(); foreach (var item in protes) { var isAttr = item.IsDefined(typeof(PromusAttribute)); if (isAttr) { var itemType = item.PropertyType; var itemTargeType = keyValuePairs[itemType.FullName]; item.SetValue(t, this.Resolve<object>(itemTargeType)); } } //字段注入 var fields = type.GetFields(); foreach (var item in fields) { var isAttr = item.IsDefined(typeof(FieldAttribute)); if (isAttr) { var itemType = item.FieldType; var itemTargeType = keyValuePairs[itemType.FullName]; item.SetValue(t, this.Resolve<object>(itemTargeType)); } } return t; } }
标签:derby ons null ring contains orm new lda obj
原文地址:https://www.cnblogs.com/mushuizzz/p/12512588.html