Enterprise Library:Unity的几个注意事项
2024-08-28 23:06:37
背景
在.Net平台中,几乎所有的Ioc容器在注册方面都不一致,使用Unity需要注意几个事项,咱们通过实验进行验证一下。
验证的内容:
- 集合的获取。
- 生命周期管理。
实验
代码
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 }
输出
结论
- ResolveAll只返回命名注册。
- 生命周期和具体类型+注册的名字有关系。
备注
使用Unity获取具体类型是不用注册的,有些Ioc容器要求所有类型都必须先注册才能获取。
最新文章
- x
- oracle 密码有效期
- C# treeview 绑定数据 【转】
- RMAN_学习笔记1_RMAN Structure概述和体系结构
- mysql查看日志
- 检查dns服务器是否可用
- Contoso 大学 - 1 - 为 ASP.NET MVC 应用程序创建 EF 数据模型
- 我在网站开发中经常用到的几个js函数01
- 深入浅出 JSTL
- 基于Zlib算法的流压缩、字符串压缩源码
- bootstrap-table 表头和内容对不齐解决办法
- Myeclipse配置优化
- BootstrapBootbox居中
- 查看oracle表空间
- Apache Kylin学习资料
- ubuntu安装带调试功能的bochs
- LwIP Application Developers Manual8---Sample lwIP applications
- 【Linux】在虚拟机上安装CentOS7
- gradle Debug的使用
- xtrabackup备份脚本