Unity wraps exception to the ResolutionFailedException. How to avoid?

后端 未结 4 1368
我在风中等你
我在风中等你 2021-01-22 12:51

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?

相关标签:
4条回答
  • 2021-01-22 13:12

    Check out ResolutionFailedException.InnerException.

    It is changing "construction service contract"

    What contract?

    IMHO the fact of objects initialization using unity should be transparent

    A point of IoC containers is to make object construction less of a focus so developers can focus on adding business value.

    that means if client waiting for example for IOException from "new" operator it should get it unwrapped also even object is created using Unity.

    Whoa, what client is using the container that expects IOException? I think you might be misusing your IoC container.

    0 讨论(0)
  • 2021-01-22 13:13

    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.

    0 讨论(0)
  • 2021-01-22 13:15

    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.

    0 讨论(0)
  • 2021-01-22 13:29

    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:

    • If you only want to catch the exceptions and log them, then add an IExceptionLogger.
    • If you want to catch the exception and manipulate the response, then replace IExceptionHandler.
    • Neither solution captures ALL exceptions. I'm still using Application_Error to capture exceptions that aren't caught within my ApiController methods.
    0 讨论(0)
提交回复
热议问题