支持.net4.0版本
public class MyXmlFactory { private IDictionaryobjectDefine = new Dictionary (); public MyXmlFactory(string fileName) { InstanceObjects(fileName); // 实例IoC容器 } /// /// 实例IoC容器 /// /// private void InstanceObjects(string fileName) { XElement root = XElement.Load(fileName); var objects = from obj in root.Elements("object") select obj; objectDefine = objects.ToDictionary( k => k.Attribute("id").Value, v => { string typeName = v.Attribute("type").Value; Type type = Type.GetType(typeName); return Activator.CreateInstance(type); } ); } ////// 获取对象 /// /// ///public object GetObject(string id) { object result = null; if (objectDefine.ContainsKey(id)) { result = objectDefine[id]; } return result; } }
xmL文件(Objects.xml):
<objects>
<object id="PersonDao" type="MyselfIoC.PersonDao, MyselfIoC" />
</objects>调用:
MyXmlFactory ctx = new MyXmlFactory(@"Objects.xml"); Console.WriteLine(ctx.GetObject("PersonDao").ToString());