现如今可能每个人都会在项目中使用着某种 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容器自动注册机制的更多相关文章

  1. Unity3.0基于约定的自动注册机制

    前文<Unity2.0容器自动注册机制>中,介绍了如何在 Unity 2.0 版本中使用 Auto Registration 自动注册机制.在 Unity 3.0 版本中(2013年),新 ...

  2. 微软IOC容器Unity简单代码示例3-基于约定的自动注册机制

    @(编程) [TOC] Unity在3.0之后,支持基于约定的自动注册机制Registration By Convention,本文简单介绍如何配置. 1. 通过Nuget下载Unity 版本号如下: ...

  3. 【tensorflow2.0】自动微分机制

    神经网络通常依赖反向传播求梯度来更新网络参数,求梯度过程通常是一件非常复杂而容易出错的事情. 而深度学习框架可以帮助我们自动地完成这种求梯度运算. Tensorflow一般使用梯度磁带tf.Gradi ...

  4. Unity容器实现自动注册

    如何创建Unity容器? 首先NuGet搜索Unity, 该示例中使用的版本为4.0.1 新建控制台程序 示例中使用常规操作, 创建一个IPay接口, 分别有两个实现类: ApplePay.Huawe ...

  5. @EnableDiscoveryClient与Nacos自动注册

    前一阵看到有篇博客说cloud从Edgware版本开始,可以不加@EnableDiscoveryClient注解,只要配置好注册中心的相关配置即可自动开启服务注册功能,比较好奇其中的原理,研究了一番特 ...

  6. thinkphp5 自动注册Hook机制钩子扩展

    Hook.php 文件已更新1.修复在linux环境下类的 \ 在basename 下无法获取到类名的问题2.修复linux 环境下无法使用hook::call 调用失败问题 请先安装thinkphp ...

  7. zabbix3.0.4 探索主机Discovery自动发现agent主机和zabbix-agent自动注册详细图文教程

    Zabbix 自动发现(Discovery)功能使用 随着监控主机不断增多,有的时候需要添加一批机器,特别是刚用zabbix的运维人员需要将公司的所有服务器添加到zabbix,如果使用传统办法去单个添 ...

  8. zabbix4.0自动注册实践

    共分为两个步骤: 1.主机zabbix_agent客户端的配置文件 2.主机zabbix_server网页端的自动注册配置 zabbix_agent配置文件 Server=192.168.100.15 ...

  9. Senparc.Weixin.MP SDK 微信公众平台开发教程(十六):AccessToken自动管理机制

    在<Senparc.Weixin.MP SDK 微信公众平台开发教程(八):通用接口说明>中,我介绍了获取AccessToken(通用接口)的方法. 在实际的开发过程中,所有的高级接口都需 ...

随机推荐

  1. mysql的从头到脚优化之数据库引擎的选择(转载)

    一. Mysql常用的存储引擎包括Innodb和Myisam以及memory引擎,但是最常用的莫过于Innodb引擎和MyISAM引擎,下边分别做下记录和比较: 下面思考下这几个问题: 你的数据库需要 ...

  2. cocos2d-js 3.0rc0加载游戏引擎时长时间黑屏

    如果是原始引擎的话是会比较大一些,但是最终发布的时候我们都建议你打包成release版,这个可以使用cocos命令 cocos compile -p web 来完成轻松打包,会在你的项目目录下创建一个 ...

  3. DataTable.Compute()用法

    DataTable.Compute()用法 2010-04-07 11:28 一.DataTable.Compute()方法說明如下 作用:          计算用来传递筛选条件的当前行上的给定表达 ...

  4. 第三方控件radupload 使用方式以及报错处理

    使用方式: 1.web.config  中需要加入: <httpHandlers>    <add verb="*" path="Telerik.Rad ...

  5. VC++ 浅谈VS2010中CMFCToolBar的用法

    本文将给大家介绍Visual Studio 2010中CMFCToolBar的用法,CMFCToolBar可以让用户自定义工具栏图标,使用静态成员函数SetUserImages()将一个CMFCToo ...

  6. VS2008中调试dll

    1.运行dll实例时,会直接弹出一个小框: 选择可拉起这个dll的exe运行就可以调试了 2.以后每次都会直接运行了,要重新选择程序,弹出上面的框,需要在project-->debugging- ...

  7. 计算机病毒实践汇总二:bufferzone沙盘使用体验

    在尝试学习分析的过程中,判断结论不一定准确,只是一些我自己的思考和探索.敬请批评指正! 1. 安装bufferzone及其简单使用 (1)安装BufferZone BufferZone的msi安装文件 ...

  8. afterTextChanged() callback being called without the text being actually changed

    afterTextChanged() callback being called without the text being actually changed up vote8down votefa ...

  9. asdsa

    ML_运营一部数据平台应用服务组 <ML_1731@pingan.com.cn> epcischagentdailyreportkb copy from OLAPSEL/frt9iora@ ...

  10. IOS开发 程序关闭状态接通知