zoukankan      html  css  js  c++  java
  • 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容器要求所有类型都必须先注册才能获取。

  • 相关阅读:
    军火库(第一期):无线电硬件安全大牛都用哪些利器?
    AMD64与IA64的区别
    win7安装apache或者php 5.7缺少vcruntime140.dll的问题
    DrawText
    Delphi与C语言类型转换对照
    chm文件打开空白无内容的解决办法
    在ubuntu 15.04下安装VMware Tools
    Vmware怎样使用nat和桥接方式解决虚拟机联网问题
    Ubuntu 14.04/14.10下安装VMware Workstation 11图文教程
    Ubuntu 16.04 安装 VMware-Workstation-12
  • 原文地址:https://www.cnblogs.com/happyframework/p/3237937.html
Copyright © 2011-2022 走看看