Unity wraps exception to the ResolutionFailedException. How to avoid?
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?
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.
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.
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.
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.
精彩评论