Unity2.0容器自动注册机制
现如今可能每个人都会在项目中使用着某种 IoC 容器,并且我们的意识中已经形成一些固定的使用模式,有时会很难想象如果没有 IoC 容器工作该怎么进展。
IoC 容器通过某种特定设计的配置,用于在运行时决定将哪些组件注入到我们的代码中。这种配置可以是基于 XML 的映射,也可以是基于 Fluent API 的设计。但随着项目代码的不断增长,配置文件总是变得越来越冗长。此时,我们该寻求某种改进措施来增强代码的可读性和可维护性。
对于 IoC 容器来讲,自动注册机制是一项非常实用的功能,并且其在某些特定的场景下特别的有效。
Unity 是微软提供的依赖注入容器,其在 2.0 版本时并不支持自动注册机制(Auto Registration),在 3.0 版本中添加了基于约定的自动注册机制(Registration By Convention)。
Codeplex 中的 Unity Auto Registration 项目通过使用 Fluent API 方式为 Unity 扩展了自动注册机制。
我们可以通过 NuGet 来添加 Unity Auto Registration 包引用。
PM> Install-Package UnityAutoRegistration
PM> Install-Package UnityAutoRegistration
Attempting to resolve dependency 'Unity (≥ 2.1.505.0)'.
Attempting to resolve dependency 'CommonServiceLocator (≥ 1.0)'.
Successfully installed 'CommonServiceLocator 1.0'.
You are downloading Unity from Microsoft, the license agreement to which is available at http://www.opensource.org/licenses/ms-pl. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Unity 2.1.505.2'.
You are downloading UnityAutoRegistration from agovorov, the license agreement to which is available at http://autoregistration.codeplex.com/license. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'UnityAutoRegistration 1.0.0.2'.
Successfully added 'CommonServiceLocator 1.0' to ConsoleApplication13_UnityAutoRegistration.
Successfully added 'Unity 2.1.505.2' to ConsoleApplication13_UnityAutoRegistration.
Successfully added 'UnityAutoRegistration 1.0.0.2' to ConsoleApplication13_UnityAutoRegistration.
Unity Auto Registration 通过使用较少的代码进行配置,自动加载、搜索和匹配指定程序集中的类和接口,并形成映射注册到 Unity 中。
using System;
using Microsoft.Practices.Unity;
using Unity.AutoRegistration; namespace ConsoleApplication13_UnityAutoRegistration
{
class Program
{
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer(); container
.ConfigureAutoRegistration()
.ExcludeSystemAssemblies()
.Include(type => type.ImplementsOpenGeneric(typeof(ICommandHandler<>)),
Then.Register().AsFirstInterfaceOfType().WithTypeName())
.ApplyAutoRegistration(); container
.ConfigureAutoRegistration()
.LoadAssemblyFrom(typeof(IRepository<>).Assembly.Location)
.ExcludeSystemAssemblies()
.Exclude(type => type.Name.Contains("_Proxy_"))
.Exclude(type => type.Name.EndsWith("_Accessor", StringComparison.Ordinal))
.Include(type => type.Implements<IBaseProvider>(), Then.Register().WithName(type => "SampleProvider"))
.Exclude(type => type.Name == "IBaseProvider")
.ApplyAutoRegistration(); container
.ConfigureAutoRegistration()
.ExcludeAssemblies(a => a.GetName().FullName.Contains("Test"))
.Include(If.Implements<ILogger>, Then.Register().UsingPerCallMode())
.Include(If.ImplementsITypeName, Then.Register().WithTypeName())
.Include(If.Implements<ICustomerRepository>, Then.Register().WithName("SampleRepository"))
.Include(If.Implements<IOrderManager>,
Then.Register()
.AsSingleInterfaceOfType()
.UsingPerCallMode())
.Include(If.DecoratedWith<LoggerAttribute>,
Then.Register()
.As<IDisposable>()
.WithTypeName()
.UsingLifetime<ContainerControlledLifetimeManager>())
.Exclude(t => t.Name.Contains("Trace"))
.ApplyAutoRegistration(); Console.ReadKey();
}
} [AttributeUsage(AttributeTargets.Class)]
public class LoggerAttribute : Attribute { }
public interface ILogger { }
[LoggerAttribute]
public class MockLogger : ILogger, IDisposable { public void Dispose() { } }
public interface IBaseProvider { }
public interface IRepository<T> { }
public interface ICustomerRepository : IRepository<Customer> { }
public class CustomerRepository : ICustomerRepository { }
public interface IOrderManager { }
public class OrderManager : IOrderManager { }
public class Customer { }
public class Order { }
public interface ICommandHandler<T> { }
public class CommandHandler<T> : ICommandHandler<T> { }
}
所以如何你仍然需要使用 Unity 2.0/2.1 版本来管理依赖注入的配置,推荐使用 Unity Auto Registration 。
Unity2.0容器自动注册机制的更多相关文章
- Unity3.0基于约定的自动注册机制
前文<Unity2.0容器自动注册机制>中,介绍了如何在 Unity 2.0 版本中使用 Auto Registration 自动注册机制.在 Unity 3.0 版本中(2013年),新 ...
- 微软IOC容器Unity简单代码示例3-基于约定的自动注册机制
@(编程) [TOC] Unity在3.0之后,支持基于约定的自动注册机制Registration By Convention,本文简单介绍如何配置. 1. 通过Nuget下载Unity 版本号如下: ...
- 【tensorflow2.0】自动微分机制
神经网络通常依赖反向传播求梯度来更新网络参数,求梯度过程通常是一件非常复杂而容易出错的事情. 而深度学习框架可以帮助我们自动地完成这种求梯度运算. Tensorflow一般使用梯度磁带tf.Gradi ...
- Unity容器实现自动注册
如何创建Unity容器? 首先NuGet搜索Unity, 该示例中使用的版本为4.0.1 新建控制台程序 示例中使用常规操作, 创建一个IPay接口, 分别有两个实现类: ApplePay.Huawe ...
- @EnableDiscoveryClient与Nacos自动注册
前一阵看到有篇博客说cloud从Edgware版本开始,可以不加@EnableDiscoveryClient注解,只要配置好注册中心的相关配置即可自动开启服务注册功能,比较好奇其中的原理,研究了一番特 ...
- thinkphp5 自动注册Hook机制钩子扩展
Hook.php 文件已更新1.修复在linux环境下类的 \ 在basename 下无法获取到类名的问题2.修复linux 环境下无法使用hook::call 调用失败问题 请先安装thinkphp ...
- zabbix3.0.4 探索主机Discovery自动发现agent主机和zabbix-agent自动注册详细图文教程
Zabbix 自动发现(Discovery)功能使用 随着监控主机不断增多,有的时候需要添加一批机器,特别是刚用zabbix的运维人员需要将公司的所有服务器添加到zabbix,如果使用传统办法去单个添 ...
- zabbix4.0自动注册实践
共分为两个步骤: 1.主机zabbix_agent客户端的配置文件 2.主机zabbix_server网页端的自动注册配置 zabbix_agent配置文件 Server=192.168.100.15 ...
- Senparc.Weixin.MP SDK 微信公众平台开发教程(十六):AccessToken自动管理机制
在<Senparc.Weixin.MP SDK 微信公众平台开发教程(八):通用接口说明>中,我介绍了获取AccessToken(通用接口)的方法. 在实际的开发过程中,所有的高级接口都需 ...
随机推荐
- sin, miss the mark, correct our aim and try again
Guilt should only be a call to action. When we see that we "missed the mark"(the meaning o ...
- 使用网易ubuntu镜像加速软件包安装
用vi工具编辑文件 sudo vi /etc/apt/sources.list 以trusty(14.04)为例,插入下面内容到文件的最前面: deb http://mirrors.163.com/u ...
- 第1章 C#类型基础
1.1值类型和引用类型 1.1.1 值类型 使用值类型之前需要对值类型的所有元素初始化(普通值类型和结构体). 结构还有一个特性:调用结构上的方法前,需要对其所有的字段进行赋值,为了避免对结构体中所有 ...
- Python全栈---5.1---装饰器
一.装饰器 执行outer函数,将index作为参数传递, 将outer函数的返回值,重新赋值给index 装饰器可以在函数执行前和执行后执行其他的附加功能,这种在代码运行期间动态增加功能的方式,称之 ...
- Notepad++ 快捷键 大全
Notepad++ 快捷键 大全Ctrl+C 复制Ctrl+X 剪切Ctrl+V 粘贴Ctrl+Z 撤消Ctrl+Y 恢复Ctrl+A 全选Ctrl+F 键查找对话框启动Ctrl+H 查找/替换对话框 ...
- 第三章 深入 ZAB 协议
上一节介绍了ZAB协议的内容,本节将从系统模型.问题描述.算法描述和运行分析四方面来深入了解 ZAB 协议. 系统模型 在一个由一组进程 n ={P1,P2,...Pn}组成的分布式系统中,每一个进程 ...
- 使用 IntraWeb (42) - 测试读取 SqLite (一)
为通过 FireDAC(XE5开始支持的) 使用 SqLite, 现在已换成 XE6 + IntraWeb v14.0.32 Ultimate. 首先把官方提供的 C:\Users\Public\Do ...
- 纵表、横表互转的SQL
纵表.横表互转的SQL By:大志若愚 1.建表: 纵表结构 Table_A create table Table_A ( 姓名 ), 课程 ), 成绩 int ) ) ) ) ) ) 姓名 课程 ...
- rm: Argument list too long
rm -rf /testdir/* -bash: /bin/rm: Argument list too long 解决: cd /testdir/; ls | xargs rm -rf
- python 内置函数 map filter reduce lambda
map(函数名,可遍历迭代的对象) # 列组元素全加 10 # map(需要做什么的函数,遍历迭代对象)函数 map()遍历序列得到一个列表,列表的序号和个数和原来一样 l = [2,3,4,5,6, ...