1.IOC简介
IOC(Inversion of Control), 控制反转
DI (Dependency Injection),依赖注入
IOC的基本概念是:不创建对象,但是描述创建它们的方式。在代码中不直接与对象和服务连接,但在配置文件中描述哪一个组件需要哪一项服务。容器负责将这些联系在一起。
2.Unity引入
3.创建单例模式容器类
using Microsoft.Practices.Unity;using Microsoft.Practices.Unity.Configuration;using System;using System.Collections.Generic;using System.Configuration;using System.Linq;using System.Text;using System.Threading.Tasks;namespace UnityIocTest{ ////// Unity IOC单例模式 /// public class UnitySingleton { //单例 private static UnitySingleton instance; //ioc容器 public IUnityContainer container; //获取单例 public static UnitySingleton getInstance() { if (instance == null || instance.container == null) { string configFile = "Unity.config"; var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFile }; //从config文件中读取配置信息 Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); //获取指定名称的配置节 UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection("unity"); instance = new UnitySingleton() { //container = new UnityContainer().LoadConfiguration((UnityConfigurationSection)ConfigurationManager.GetSection("unity"), "MyContainer") container = new UnityContainer().LoadConfiguration(section, "MyContainer") //container = new UnityContainer() }; //instance.container.RegisterType(); } return instance; } //IOC注入实体 public static T GetInstanceDAL () { return getInstance().container.Resolve (); } }}
此处是将Unity config配置单独成一个文件,方便管理。
4.添加IOC相关类
接口类
public interface IExampleClass{ void DoHelloWord();}
具体实现类
public class ExampleClass : IExampleClass { public void DoHelloWord() { Console.WriteLine("Hello Word!"); } }
实现类扩展
public class DIExampleClass { //属性注入 [Dependency] public IExampleClass example { get; set; } private IExampleClass testInject; public void DoWork() { example.DoHelloWord(); testInject.DoHelloWord(); } //方法注入 [InjectionMethod] public void Initialize(IExampleClass instance) { testInject = instance; } }
5.添加配置文件Unity.config
6.函数调用
class Program { static void Main(string[] args) { //var dao = UnitySingleton.GetInstanceDAL(); var dao = UnitySingleton.GetInstanceDAL (); dao.DoWork(); Console.ReadLine(); } }
7.结果显示
Hello Word!
Hello Word!