講了這麼多理論,我們來手動實現一個簡易的IoC{
tagshow(event)
}">架構的,這樣可以加深IoC的理論知識。
一、思路
在我們使用Spring.NET架構的時候,首先需要執行個體化Spring.NET容器, 然後調用IoC容器IObjectFactory{
tagshow(event)
}">介面中GetObject方法擷取容器中的對象。通過這一點就可以告訴我們製作IoC容器需要寫一個擷取 XML檔案內容的方法和申明一個Dictionary<string, object>來存放IoC容器中的對象,還需要寫一個能從Dictionary<string, object>中擷取對象的方法。
二、分析
要擷取XML檔案的內容,在3.5的文法中,我自然而然想到了Linq To XML。需要執行個體XML中{
tagshow(event)
}">配置的對象,我們想到了使用反射技術來擷取對象的執行個體。
三、代碼實現
1.xml工廠
MyXmlFactory
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Xml.Linq;
- using System.Reflection;
- namespace MyselfIoC
- {
- public class MyXmlFactory
- {
- private IDictionary<string, object> objectDefine = new Dictionary<string, object>();
- public MyXmlFactory(string fileName)
- {
- InstanceObjects(fileName); // 執行個體IoC容器
- }
- /// <summary>
- /// 執行個體IoC容器
- /// </summary>
- /// <param name="fileName"></param>
- 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);
- }
- );
- }
- /// <summary>
- /// 擷取對象
- /// </summary>
- /// <param name="id"></param>
- /// <returns></returns>
- public object GetObject(string id)
- {
- object result = null;
- if (objectDefine.ContainsKey(id))
- {
- result = objectDefine[id];
- }
- return result;
- }
- }
- }
複製代碼
2.調用
Program
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace MyselfIoC
- {
- class Program
- {
- static void Main(string[] args)
- {
- AppRegistry();
- Console.ReadLine();
- }
- static void AppRegistry()
- {
- MyXmlFactory ctx = new MyXmlFactory(@"D:\Objects.xml");
- Console.WriteLine(ctx.GetObject("PersonDao").ToString());
- }
- }
- }
複製代碼
好了,一個簡易的IoC架構就基本實現了