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(通用接口)的方法. 在实际的开发过程中,所有的高级接口都需 ...
随机推荐
- Java串口通信详解
http://blog.csdn.net/kabini/article/details/1601324 ———————————————————————————————————————————————— ...
- Mycat配置文件schema.xml参数配置
Mycat原理: Mycat的原理中最重要的一个动词是"拦截",它拦截了用户发送过来的SQL语句,首先对SQL语句做了一些特定的分析:如分片分析.路由分析.读写分离分析.缓存分析等 ...
- Linux_08------Linux的系统管理
分钟,在随机延迟0-45分钟时间 * 使用nice命令指定默认优先级,使用run-parts脚本执行/etc/cron.daily目录中的所有可执行文件. * */
- Sql 邮件发送
select name from msdb.dbo.sysmail_profile --邮件发送日志 SELECT * FROM msdb.dbo.sysmail_event_log delete F ...
- [转载] Android中Xposed框架篇---利用Xposed框架实现拦截系统方法
本文转载自: http://www.wjdiankong.cn/android%E4%B8%ADxposed%E6%A1%86%E6%9E%B6%E7%AF%87-%E5%88%A9%E7%94%A8 ...
- Android消息推送——JPush极光推送
刚看了一篇关于Android消息推送评测总结的博客http://www.cnblogs.com/logan/p/4514635.html: 自己也对原学过的JPush极光进行一下小结,方便后续工作使用 ...
- step2-------使用myeclipse创建maven java web项目
1.文章内容概述: 在对项目需求进行分析之后,决定使用maven对我的java web项目进行管理,这篇文章记录了使用myeclipse创建maven java web项目的过程. 2.开发环境: j ...
- linux关闭防火墙
查看防火墙状态: sudo service iptables status linux关闭防火墙命令: sudo service iptables stop linux启动防火墙命令: sudo se ...
- html+css-----补
其实html没什么好补充的了,主要是使用css如何构造出各种想要的效果 1.加减框 <!DOCTYPE html> <html lang="en"> < ...
- Light OJ 1026 - Critical Links (图论-双向图tarjan求割边,桥)
题目大意:双向联通图, 现在求减少任意一边使图的联通性改变,按照起点从小到大列出所有这样的边 解题思路:双向边模版题 tarjan算法 代码如下: #include<bits/stdc++.h& ...