Enterprise Library:Unity的幾個注意事項


背景

在.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容器要求所有類型都必須先注冊才能獲取。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM