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(通用接口)的方法. 在实际的开发过程中,所有的高级接口都需 ...
随机推荐
- Excel_常用快捷键
Ctrl+B 粗体Ctrl+U 下划线Ctrl+I 斜体Ctrl+5 删除线Ctrl+9 隐藏选中的行Ctrl+0 隐藏选中 ...
- Linux内核启动logo
之前在分析samsung的fb驱动代码的时候,其中有一段代码是处理内核logo显示相关的,今天就内核logo这个话题来聊一聊! 一.处理内核logo显示相关的代码在哪? 回到samsung的fb驱动代 ...
- 2.Mybatis入门程序(单表的增删改成)
这里讲的单表的增删改查,是由mapper代理的增删改查,先来看看步骤: 1.jar包的导入 2.配置全局的配置文件 3.建立接口 4.编写mapper.xml 5.测试 工程结构:这个你们自己可以调整 ...
- Asp.net Session 保存到MySql中
一 网站项目引入"mysql.web.dll" 二 web.config配置中添加mysql数据库连接字符串 <connectionStrings> <remov ...
- mac--有用的命令和快捷键
有用的命令: 将man命令打开为pdf文件预览 man -t grep | open -f -a Preview 定位某文件的位置 locate htop 隐藏和显示桌面文件 chflags hidd ...
- AngularJS学习--- AngularJS中XHR(AJAX)和依赖注入(DI) step5
前言:本文接前一篇文章,主要介绍什么是XHR,AJAX,DI,angularjs中如何使用XHR和DI. 1.切换工具目录 git checkout -f step- #切换分支 npm start ...
- JavaScript求最大数最小数
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8" ...
- 初入Cocos2d-x 2.2
下载2.2,用迅雷离线下载很快搞定. 解压后,打开cocos2d-win32.vc2012.sln,编译,超慢,20分钟才完事. 然后想创建一个新项目,需要用到python,用python3.3运行脚 ...
- iOS IPv6兼容支持和IPv6审核被拒收集整理
最近遇到一个大坑:IPv6审核被拒问题,于是广寻解决方案,先把一些可以用资料文档收集起来备用.也希望同行能用得着. 官方文档说明:Supporting IPv6 DNS64/NAT64 Network ...
- serialVersionUID的作用 (zz)
serialVersionUID的作用 2011-05-12 16:04:19| 分类: java|举报|字号 订阅 在很多应用中,需要对某些对象进行序列化,让它们离开内存空间,入住物理硬盘 ...