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

  • 相关阅读:
    字典和列表 相互嵌套
    HashSet
    SQLServer在分页获取数据的同时获取到总记录数
    C# list 多条件排序
    DictionaryBase
    .Net页面数据校验类(WebForm)
    链接
    解决:Server's certificate is not trusted
    win10下gradle6.2版本下载安装配置
    解决:mysql5.7乱码中文
  • 原文地址:https://www.cnblogs.com/happyframework/p/3233038.html
Copyright © 2020-2023  润新知