2.自己搭建的一个简易的ioc容器

时间:2023-12-16 22:51:44

1.persondao类
namespace MyselfIoC
{
    public class PersonDao
    {
        public override string ToString()
        {
            return "我是PersonDao";
        }
    }
}
2.xml 工厂文件
<?xml version="1.0" encoding="utf-8" ?>

<objects>

<object id="PersonDao" type="MyselfIoC.PersonDao, MyselfIoC" />
 
</objects>
3.工厂ioc 构造函数实例化一个ioc工厂的字典

namespace MyselfIoC
{
    public class MyXmlFactory
    {
        private IDictionary<string, object> objectDefine = new Dictionary<string, object>();

public MyXmlFactory(string fileName)
        {

//构造函数实例IoC容器
            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;
        }
    }
}

4.调用部分

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());
        }
    }
}