zoukankan      html  css  js  c++  java
  • Unity的Deferring the Resolution of Objects

    Unity给出一种延迟创建对象的方案,可以先获取对象的创建器 -> 再注册类型 -> 其余代码 -> 创建类型实例,创建器的类型必须是Func<T>,而不是和Func相同返回值的delegate。看一个简单示例:

    1 UnityContainer unityContainer = new UnityContainer();
    2 unityContainer.LoadConfiguration();
    3 
    4 Func<TextWriter> createFactory = unityContainer.Resolve<Func<TextWriter>>();
    5 
    6 unityContainer.RegisterType<TextWriter, StringWriter>(new InjectionConstructor());
    7 
    8 TextWriter textWriter = createFactory();

    由于4.0默认新增了Lazy<T>(3.5可以添加并行库System.Threading.dll的引用),可以将类型的创建延迟,稍做修改后的代码:

    1 IUnityContainer unityContainer = new UnityContainer();
    2 unityContainer.LoadConfiguration();
    3 
    4 Func<TextWriter> createFactory = unityContainer.Resolve<Func<TextWriter>>();
    5 
    6 unityContainer.RegisterType<TextWriter, StringWriter>(new InjectionConstructor());
    7 
    8 Lazy<TextWriter> textWriter = new Lazy<TextWriter>(createFactory);

     

     

  • 相关阅读:
    小数化分数2
    Sum of divisors
    Subsequence
    Lowest Bit
    Specialized Four-Digit Numbers
    Hunters
    Pet
    测试你是否和LTC水平一样高
    Bank Interest
    bzoj 1295
  • 原文地址:https://www.cnblogs.com/junchu25/p/2631536.html
Copyright © 2011-2022 走看看