简体   繁体   English

使用命名注册解析实例不会引发异常

[英]Resolve instance using named registration does not throw Exception

I thought I know a lot about Unity, but the following scenario I did not except. 我以为我对Unity有很多了解,但是以下情况我并非没有。 I´m using Unity Container to register my views for Prism as objects with a named registration like so: 我正在使用Unity Container将我对Prism的视图注册为具有命名注册的对象,如下所示:

_unityContainer.RegisterType<object, MyDummyView>("MyDummyViewName");

and I request instance of the view by calling 我通过调用请求视图的实例

object view = _unityContainer.Resolve<object>("MyDummyViewName");

So far so good. 到现在为止还挺好。 Now I found a bug in my system, cause I used the wrong name to resolve an instance of a view and I expected an exception to be thrown by Unity. 现在,我在系统中发现一个错误,原因是我使用了错误的名称来解析视图的实例,并且我期望Unity会引发异常。

object view = _unityContainer.Resolve<object>("MyWrongDummyViewName");

But Unity does not throw any exception (like ResolutionFailedException or ActivationException ). 但是Unity不会引发任何异常(例如ResolutionFailedExceptionActivationException )。 It returns a new object , when I do the call above, without registering any view with the given (wrong) name. 当我进行上述调用时,它返回一个新object ,而没有使用给定(错误)名称注册任何视图。

Is this a correct behavior by Unity? 这是Unity的正确行为吗? I really expected to get an exception here. 我真的希望在这里得到一个例外。 In the scope of Prism this is a problem, cause I won´t get any exceptions during navigation to a wrong target (view). 在Prism的范围内,这是一个问题,因为导航到错误的目标(视图)时我不会遇到任何异常。

I'm with you that this is unexpected behavior. 我与你在一起,这是意外行为。 I think the problem origins from the fact that you are trying to resolve an instance of a concrete class (in your case object ). 我认为问题源于您试图解析具体类的实例(在您的情况下为object )的事实。 Looks like Unity will always try to resolve that instance. 看起来Unity总是会尝试解析该实例。 As long as it can do that it will ignore named mappings. 只要能够做到,它将忽略命名映射。

I experimented with a base class ( ViewBase ) which the container will also resolve unless you declare it abstract . 我尝试了一个基类( ViewBase ),除非您将其声明为abstract否则容器也将解析该基类。 Doing that raises the expected exception. 这样做会引发预期的异常。

If you introduce an interface or abstract base class that should solve your problem. 如果您引入了可以解决问题的接口或抽象基类。

You should open a bug ticket for Unity . 您应该为Unity打开一个故障单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM