C# IOC 个人理解

  学习QFramework 过程中发现对IOC不太了解,就大概百度了一下思路

   将原先类与类之间的相互依赖关系,转移到第三方容器中,

同过读取配置文件来生成对应的依赖关系,将原本类之间的耦合转移到配置文件中。

  这是我大概的一个理解,欢迎大家斧正。

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml.Linq;
using UnityEngine;

public class Test : MonoBehaviour
{
    object user = new object();
    private void Start()
    {
        var container = IoCContainer.GetContainer();

        User userIoc = container[" "] as User;
        userIoc.Say();
    }
}

public class User
{
    public void Say()
    {
        Debug.Log(" 抱树");
    }
}

public class IoCContainer
{
    private static Dictionary<string, object> container = new Dictionary<string, object>();

    public static Dictionary<string, object> GetContainer()
    {
        LoadContainer();
        return container;
    }


    /// <summary>
    /// 加载填充容器
    /// </summary>
    private static void LoadContainer()
    {
        //获取项目的根目录的绝对路径 ,
        //因为测试时应用生成在'根目录/bin/Debug' 所以需要向上走两个目录
        string rootPath = Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + @"..\..\");
        // 加载config文件
        XElement xElement = XElement.Load(rootPath + "App.config");
        //获取myobjects节点下的子集合
        IEnumerable<XElement> items = xElement.Descendants("myobjects").Elements();
        //循环实例化节点
        foreach (var item in items)
        {
            //通过反射加载程序集
            var assembly = Assembly.LoadFrom(item.Attribute("assembly").Value);
            //创建实例
            var entity = assembly.CreateInstance(item.Attribute("type").Value);
            //添加到容器中
            container.Add(item.Attribute("name").Value, entity);
        }

    }
}

 

posted @ 2021-09-09 11:04  D个人笔记  阅读(375)  评论(0编辑  收藏  举报