Unity 将异常包装到 ResolutionFailedException。如何避免?
我想知道,是否有可能要求 Unity“在解析时不包装任何用户异常”?
确实,为什么 Unity 会对 ResolutionFailedException 进行包装?它正在改变“构建服务合同”,恕我直言,使用 Unity 进行对象初始化的事实应该是透明的,这意味着如果客户端等待来自“new”操作符的 IOException,它应该将其解开,即使对象是使用 Unity 创建的。
其他 IoC 容器的行为是否相同?
I want to know, is there the possibility to ask Unity "do not wrap any user exceptions at resolve time"?
Really, why Unity do wrappings to ResolutionFailedException? It is changing "construction service contract", IMHO the fact of objects initialization using unity should be transparent, that means if client waiting for example for IOException from "new" operator it should get it unwrapped also even object is created using Unity.
Do other IoC containers behave the same?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为您的构造函数不应包含任何逻辑。
我知道这不是一个完全令人满意的答案,但我不知道您可以在 Unity 中关闭此行为 - 我也确实同意这是一个奇怪的设计决策...
但是,如果您保留你的构造函数很简单,你不会有这个问题。
Because your constructors should contain no logic.
I know that's not a completely satisfying answer, but I'm not aware that you can switch off this behavior in Unity - I also do agree that it's a strange design decision...
However, if you keep your constructors simple, you will not have that problem.
查看ResolutionFailedException.InnerException。
什么合同?
IoC 容器的一个要点是减少对象构造的焦点,以便开发人员可以专注于增加业务价值。
哇哦,哪个客户端正在使用需要
IOException
的容器?我认为您可能误用了 IoC 容器。Check out
ResolutionFailedException.InnerException
.What contract?
A point of IoC containers is to make object construction less of a focus so developers can focus on adding business value.
Whoa, what client is using the container that expects
IOException
? I think you might be misusing your IoC container.Unity 包装异常的原因完全与契约有关 - Resolve 方法的契约。
当 Resolve 抛出异常时,应用程序应该捕获什么?假设您确实解析了一个您知道会抛出 IOException 的类。因此,您可以在解析调用周围捕获该异常。
然后实现发生变化。或者只是配置。现在服务抛出了其他东西。
现在您已经进行了配置更改,需要更改代码。不好。
第二个原因是,通过包装的异常,容器可以放置有关解析过程中发生故障的位置的诊断信息。
The reason Unity wraps exceptions is all about the contract - the contract of the Resolve method.
What should an application catch when Resolve throws? Suppose you did resolve a class that you know throws IOException. So you put a catch for that exception around the resolve call.
Then the implementation changes. Or just the configuration. Now the services throw something else.
Now you've got a configuration change that will require a code change. Not good.
A second reason that with the wrapped exception the container has a place to put diagnostic information about where in the resolve process the failure occurred.
我有类似的需求,并在这里找到了解决方案: 捕获 ASP.NET Web Api 中所有未处理的异常
这是我在查看链接文章中的答案时了解到的内容:
I had a similar need and found a solution here: catch all unhandled exceptions in ASP.NET Web Api
Here's what I learned when reviewing answers from the linked article: