Unity2.0容器自动注册机制

时间:2021-11-12 03:16:05

现如今可能每个人都会在项目中使用着某种 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&period;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&period;0】自动微分机制

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

  4. Unity容器实现自动注册

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

  5. &commat;EnableDiscoveryClient与Nacos自动注册

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

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

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

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

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

  8. zabbix4&period;0自动注册实践

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

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

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

随机推荐

  1. JavaScript系列:计算一个结果为30的加法智力题

    用下面这段JavaScript代码可以计算出来 function findTheThreeNum(numFix) { var a = ["1", "3", &q ...

  2. What is the PPA and How to do with it &quest;

    Part of the appeal of Ubuntu is its six-month release cycle. Every six months a new version of the f ...

  3. iOSQuartz2D-04-手动剪裁图片并保存到相册

    实现效果 操作步骤 绘制一个矩形框,弹出一个alertView,提示是否保存图片 点击"是",将图片保存到相册 在相册中查看保存的图片 效果图 实现思路 在控制器的view上添加一 ...

  4. Git教程之管理修改&lpar;6&rpar;

    Git比其他版本控制系统设计得优秀,因为Git跟踪并管理的是修改,而非文件.你会问,什么是修改?比如你新增了一行,这就是一个修改,删除了一行,也是一个修改,更改了某些字符,也是一个修改,删了一些又加了 ...

  5. 2015第40周二Node学习

    node历史 今天看cnode开源项目用了io.js,在查这个项目时发现这篇文章node历史,node.js和io.js关系谈到Node.js的由来,不可避免要聊到它的创始人Ryan Dahl.在20 ...

  6. C&num; 入门经典

    C#简介 使用.NETFrmework的含义 使用.NETFrmework的一个重要原因是他可以作为集成各种操作系统的方式 包含了一个非常大的代码库 除了提供这个库以外.NETFrmework还包含. ...

  7. MySQL性能调优——锁定机制与锁优化分析

    针对多线程的并发访问,任何一个数据库都有其锁定机制,它的优劣直接关系着数据的一致完整性与数据库系统的高并发处理性能.锁定机制也因此成了各种数据库的核心技术之一.不同数据库存储引擎的锁定机制是不同的,本 ...

  8. Lintcode415-Valid Palindrome-Medium

    Given a string, determine if it is a palindrome, considering only alphanumeric(字母和数字) characters and ...

  9. ckeditor 实现ctrl&plus;v粘贴图片并上传、word粘贴带图片

    公司做的项目需要用到文本上传功能. Chrome+IE默认支持粘贴剪切板中的图片,但是我要粘贴的文章存在word里面,图片多达数十张,我总不能一张一张复制吧? 我希望打开文档doc直接复制粘贴到富文本 ...

  10. Content-Type:几种常用数据编码格式

    Content-Type: 用于定义用户的浏览器或相关设备如何显示将要加载的数据,或者如何处理将要加载的数据. 内容类型,一般指网页中存在的Content-Type,Content-Type属性指定请 ...