实现一个简易的IoC框架(上)(此篇与Spring.NET无关,为自己手写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

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框架就基本实现了。

原文地址:https://www.cnblogs.com/millen/p/1635906.html