【问题标题】:Is it possible to disable the auto-instantiation behaviour of the UnityContainer?是否可以禁用 UnityContainer 的自动实例化行为?
【发布时间】:2011-05-26 15:36:29
【问题描述】:

UnityContainer.Resolve() 将实例化没有通过反射显式注册的类,允许这样的事情:

using System;
using Microsoft.Practices.Unity;

namespace ConsoleApplication2
{
    public class Foo
    {
        public void SayHello()
        {
            Console.WriteLine("Hello");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var container = new UnityContainer();
            var foo = container.Resolve<Foo>();
            foo.SayHello();
        }
    }
}

我的问题是,如果我愿意,可以禁用此行为,这样类就不会自动解析(引发异常或返回 null?)

【问题讨论】:

    标签: .net unity-container ioc-container


    【解决方案1】:

    它不是内置的,但您可以编写一个容器扩展来改变这种行为。这将需要两件事 - 首先,一个用于记录类型何时在策略列表中注册的注册事件的处理程序,其次,一个将检查“已注册”策略并在它不存在时抛出的策略。

    如果您熟悉编写扩展程序,它相当小而且很容易做到。很遗憾,我现在没有时间整理一个,抱歉。

    【讨论】:

    【解决方案2】:

    您可以通过传递注册名称来使用Resolve&lt;&gt;(),如here 所述。所以尝试传递一个不存在的注册名称,看看会发生什么。希望这将绕过 Unity 的反射逻辑并返回一个 NULL 对象。

    【讨论】:

    • 不,自动创建逻辑保持不变 - 名称只是内部注册列表的一个键。如果在列表中没有找到任何内容,则默认启动。
    • 感谢您澄清这一点。我会在此处保留此答案,以防其他人需要知道这一点。
    【解决方案3】:

    考虑使用接口。 像这样的:

    interface IFoo{...}
    class Foo:IFoo{...}
    // ...
    var foo = container.Resolve<IFoo>(); // Exception here
    

    【讨论】:

      猜你喜欢
      • 2020-05-13
      • 2021-10-04
      • 2011-04-13
      • 2021-05-09
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      相关资源
      最近更新 更多