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容器要求所有类型都必须先注册才能获取。

  • 相关阅读:
    Ubuntu安装php7.0环境
    PHP-FPM参数详情
    phpize是干嘛的
    Ubuntu忘记密码
    Ubuntu下面删除和卸载软件
    Js验证正则表达式
    JS发送验证码;并设置cookie
    Shell脚本之sed的使用
    Bash基本功能:输入输出重定向
    shell常用快捷键
  • 原文地址:https://www.cnblogs.com/happyframework/p/3237937.html
Copyright © 2011-2022 走看看