Spring.NET学习笔记3——实现一个简易的IoC框架(练习篇)

讲了这么多理论,我们来手动实现一个简易的IoC框架的,这样可以加深IoC的理论知识。

  一、思路

在我们使用Spring.NET框架的时候,首先需要实例化Spring.NET容器, 然后调用IoC容器IObjectFactory接口中GetObject方法获取容器中的对象。通过这一点就可以告诉我们制作IoC容器需要写一个获取 XML文件内容的方法和申明一个Dictionary<string, object>来存放IoC容器中的对象,还需要写一个能从Dictionary<string, object>中获取对象的方法。

  二、分析

要获取XML文件的内容,在3.5的语法中,我自然而然想到了Linq To XML。需要实例XML中配置的对象,我们想到了使用反射技术来获取对象的实例。
  

  三、代码实现

1.xml工厂

MyXmlFactory

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Xml.Linq;
  6. using System.Reflection;
  7. namespace MyselfIoC
  8. {
  9.     public class MyXmlFactory
  10.     {
  11.         private IDictionary<string, object> objectDefine = new Dictionary<string, object>();
  12.         public MyXmlFactory(string fileName)
  13.         {
  14.             InstanceObjects(fileName);  // 实例IoC容器
  15.         }
  16.         /// <summary>
  17.         /// 实例IoC容器
  18.         /// </summary>
  19.         /// <param name="fileName"></param>
  20.         private void InstanceObjects(string fileName)
  21.         {
  22.             XElement root = XElement.Load(fileName);
  23.             var objects = from obj in root.Elements("object") select obj;
  24.             objectDefine = objects.ToDictionary(
  25.                     k => k.Attribute("id").Value,
  26.                     v =>
  27.                     {
  28.                         string typeName = v.Attribute("type").Value; 
  29.                         Type type = Type.GetType(typeName); 
  30.                         return Activator.CreateInstance(type);
  31.                     }
  32.                 );
  33.         }
  34.         /// <summary>
  35.         /// 获取对象
  36.         /// </summary>
  37.         /// <param name="id"></param>
  38.         /// <returns></returns>
  39.         public object GetObject(string id)
  40.         {
  41.             object result = null;
  42.             if (objectDefine.ContainsKey(id))
  43.             {
  44.                 result = objectDefine[id];
  45.             }
  46.             return result;
  47.         }
  48.     }
  49. }
复制代码

2.调用

Program

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace MyselfIoC
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             AppRegistry();
  12.             Console.ReadLine();
  13.         }
  14.         static void AppRegistry()
  15.         {
  16.             MyXmlFactory ctx = new MyXmlFactory(@"D:\Objects.xml");
  17.             Console.WriteLine(ctx.GetObject("PersonDao").ToString());
  18.         }
  19.     }
  20. }
复制代码

好了,一个简易的IoC框架就基本实现了

posted @ 2011-03-26 20:43  似水流年-johnhuo  阅读(269)  评论(1编辑  收藏  举报