C#简易IOC
标签:derby ons null ring contains orm new lda obj
interface ImContainer
{
void RegisterType() where TTo : TForm;
TForm Resolve();
}
class mContainer : ImContainer
{
private Dictionarystring, Type> keyValuePairs = new Dictionarystring, Type>();
public void RegisterType() where TTo : TForm
{
keyValuePairs.Add(typeof(TForm).FullName, typeof(TTo));
}
public T Resolve()
{
Type type = keyValuePairs[typeof(T).FullName];
return Resolve(type);
}
private T Resolve(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();
}
Listobject> list = new Listobject>();
foreach (var item in ctor.GetParameters())
{
var itemType = item.ParameterType;
var itemTargeType = keyValuePairs[itemType.FullName];
var target = this.Resolveobject>(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.Resolveobject>(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.Resolveobject>(itemTargeType));
}
}
return t;
}
}
C#简易IOC
标签:derby ons null ring contains orm new lda obj
原文地址:https://www.cnblogs.com/mushuizzz/p/12512588.html
文章来自:
搜素材网的
编程语言模块,转载请注明文章出处。
文章标题:
C#简易IOC
文章链接:http://soscw.com/index.php/essay/64335.html
评论