背景

在.Net平台中,几乎所有的Ioc容器在注册方面都不一致,使用Unity需要注意几个事项,咱们通过实验进行验证一下。

验证的内容:

  1. 集合的获取。
  2. 生命周期管理。

实验

代码

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 using Microsoft.Practices.Unity;
8
9 namespace UnityStudy
10 {
11 class Program
12 {
13 static void Main(string[] args)
14 {
15 UnityContainer container = new UnityContainer();
16
17 container.RegisterType<ITest, Test>(new PerThreadLifetimeManager());
18 container.RegisterType<ITest, TestA>("A");
19 container.RegisterType<ITest, TestB>("B");
20 container.RegisterType<ITest, Test>("C");
21 container.RegisterType<Test, Test>();
22 container.RegisterType<IOther, Test>();
23
24 Console.WriteLine(container.ResolveAll<ITest>().Count());
25 //输出:3
26
27 Console.WriteLine(container.Resolve<ITest>().GetHashCode());
28 Console.WriteLine(container.Resolve<ITest>().GetHashCode());
29
30 Console.WriteLine(container.Resolve<Test>().GetHashCode());
31 Console.WriteLine(container.Resolve<Test>().GetHashCode());
32
33 Console.WriteLine(container.Resolve<IOther>().GetHashCode());
34 Console.WriteLine(container.Resolve<IOther>().GetHashCode());
35 //输出:上边六行输出内容一样
36
37 Console.WriteLine(container.ResolveAll<ITest>().Last().GetHashCode());
38 Console.WriteLine(container.ResolveAll<ITest>().Last().GetHashCode());
39 //输出:输出两行完全不一样
40 }
41 }
42
43 public interface ITest { }
44
45 public interface IOther { }
46
47 public class Test : ITest, IOther { }
48
49 public class TestA : ITest { }
50
51 public class TestB : ITest { }
52 }

输出

结论

  1. ResolveAll只返回命名注册。
  2. 生命周期和具体类型+注册的名字有关系。

备注

使用Unity获取具体类型是不用注册的,有些Ioc容器要求所有类型都必须先注册才能获取。

最新文章

  1. x
  2. oracle 密码有效期
  3. C# treeview 绑定数据 【转】
  4. RMAN_学习笔记1_RMAN Structure概述和体系结构
  5. mysql查看日志
  6. 检查dns服务器是否可用
  7. Contoso 大学 - 1 - 为 ASP.NET MVC 应用程序创建 EF 数据模型
  8. 我在网站开发中经常用到的几个js函数01
  9. 深入浅出 JSTL
  10. 基于Zlib算法的流压缩、字符串压缩源码
  11. bootstrap-table 表头和内容对不齐解决办法
  12. Myeclipse配置优化
  13. BootstrapBootbox居中
  14. 查看oracle表空间
  15. Apache Kylin学习资料
  16. ubuntu安装带调试功能的bochs
  17. LwIP Application Developers Manual8---Sample lwIP applications
  18. 【Linux】在虚拟机上安装CentOS7
  19. gradle Debug的使用
  20. xtrabackup备份脚本

热门文章

  1. Java打包问题之一:打包出现java.io.IOException: invalid header field
  2. radis相关操作
  3. ConcurrentMap
  4. pandas 数据结构的基本功能
  5. Weblogic常用监控指标以及监控工具小结
  6. IE8/9的几个前端bug解决方案
  7. Ubuntu16.4 修改静态ip地址
  8. plan-6.17周末
  9. WPS Office 2012 专业版 附正版序列号
  10. 宝塔面板php扩展安装