C# Ioc容器Unity,简单实用

开头先吐槽一下博客园超级不好用,添加图片后就写不动字了,难道是bug

好进入正题,先来说下依赖注入,简单来说就是定义好接口,上层代码调用接口,具体实现通过配置文件方式去指定具体实现类。

首先我们需要通过nuget来安装unity

安装好后就可以写一个方法类去实现依赖注入

public class UnityIocHelper : IServiceProvider
    {
        private readonly IUnityContainer _container;
        private static readonly UnityIocHelper dbinstance = new UnityIocHelper("DBcontainer");
        private UnityIocHelper(string containerName)
        {
            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
            _container = new UnityContainer();
            section.Configure(_container, containerName);
        }

        public static UnityIocHelper DBInstance
        {
            get { return dbinstance; }
        }
        public object GetService(Type serviceType)
        {
            return _container.Resolve(serviceType);
        }
        public T GetService()
        {
            return _container.Resolve();
        }
        public T GetService(params ParameterOverride[] obj)
        {
            return _container.Resolve(obj);
        }
        public T GetService(string name, params ParameterOverride[] obj)
        {
            return _container.Resolve(name, obj);
        }
    }

具体调用方法

public static IDatabase Base(string connString)
        {
            return UnityIocHelper.DBInstance.GetService(“MySql”, new ParameterOverride(
              "connString", connString));
        }

配置信息


  
    "IDatabase" type="LRMC.Data.IDatabase,LRMC.Data" />
    "SqlServer" type="LRMC.Data.SqlDapper.Database,LRMC.Data.SqlDapper" />
    "MySql"     type="LRMC.Data.MySqlDapper.Database,LRMC.Data.MySqlDapper" />
  
  
    "DBcontainer">
      
      "IDatabase" mapTo="SqlServer" name="SqlServer">
      "IDatabase" mapTo="MySql" name="MySql">
    
  
typeAlias 指定一个类的别名,
就是
IDatabase这个接口通过
MySql(
LRMC.Data.MySqlDapper.Database
)这个类去实现。



                                                       
                                                       
                                                       
                                                       
                                                       
                                                       
                                                       
                                                       
                                                       
                                                       
                                                       
                                                       
                                                       
                                                       
                                                       

 

你可能感兴趣的:(C# Ioc容器Unity,简单实用)