简介:

       IOC设计模式是控制反转模式,即依赖注入。常规的新建对象是通过new来实现,对象不一样时需要更改程序。而通过IOC仅仅修改配置文件即可实现不同对象的新建。亦可通过NuGet使用第三方Autofac。

 

介绍:

  1. IOC(inversion of control)控制反转模式,控制反转是将组件间的依赖关系从程序内部提到外部来管理。
  2. DI(dependency injection)依赖注入模式,依赖注入是指将组件的依赖通过外部以参数或其他形式注入。
  3. 对象的创建不依赖new,而是依赖于IOC容器,而IOC容器依赖xml文件(或其它文件)。对象的创建仅需修改配置文件,无需修改代码。

 

使用:

本案例是创建一个学生的对象,根据名字的区别,区分对象的不一样。案例的使用场景并非十分的完美。大家根据实际需求的不一样,灵活运用,思想很重要。

  • Student类
    public class Student
    {
        public string Name { get; set; }

        public void DoSomething()
        {
           
        }
    }
  • xml读写 
 public class XmlFile
    {
        public static object Load(Type type, string fullPath)
        {
            object obj = null;
            try
            {
                if (fullPath == null) return null;

                using (FileStream reader = new FileStream(fullPath, FileMode.Open))
                {
                    XmlSerializer serial = new XmlSerializer(type);
                    obj = serial.Deserialize(reader);
                }
            }
            catch (Exception ex)
            {

            }

            return obj;
        }
        public static void Save(object obj, string fullPath)
        {
            try
            {
                if (obj == null || fullPath == null) return;
                Type tempType = obj.GetType();

                using (TextWriter writer = new StreamWriter(fullPath))
                {
                    XmlSerializer serial = new XmlSerializer(tempType);
                    serial.Serialize(writer, obj);
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
  • IOC 
    public class Ioc
    {
        //容器对象
        private static Dictionary<string, object> Container = new Dictionary<string, object>();
        private static string FilePath = Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + @"..\..\") + "Student.xml";

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

        //读取配置
        private static void LoadContainer()
        {   
            Student stu = (Student)XmlFile.Load(typeof(Student), FilePath);
            if (stu != null)
            {
                Container.Add(stu.Name, stu);
            }
        }
        
        //保存配置
        public static void SaveContanier(Student stu)
        {
            XmlFile.Save(stu, FilePath);
        }
    }
  • 测试 
            //保存一个xml配置文件,后续更改仅需手动更改配置
            Student student = new Student();
            student.Name = "张三";
            Ioc.SaveContanier(student);

            //获取容器对象,还需要判断对象是否存在
            var cont = Ioc.GetContainer();
            Student stu = cont["张三"] as Student;
            stu.DoSomething();

 

Logo

Authing 是一款以开发者为中心的全场景身份云产品,集成了所有主流身份认证协议,为企业和开发者提供完善安全的用户认证和访问管理服务

更多推荐