文章教程

.NET Unity IOC框架使用实例详解

5/9/2018 9:51:11 PM 人评论 次浏览

.NET Unity IOC框架的使用实例,具体内容如下

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
{
 /// <summary>
 /// Unity IOC单例模式 
 /// </summary>
 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<IExampleClass, ExampleClass>();
   }
   return instance;
  }

  //IOC注入实体
  public static T GetInstanceDAL<T>()
  {
   return getInstance().container.Resolve<T>();
  }
 }
}