I want to use my child class like this:
throw new MyCustomException()
And I whenever this be invoke I want to wrap it with correlation id which suppose to be injected by the service. I want to inject it to the base class to avoid writing like that
throw new MyCustomException(correlationID)
but I don't know how to do it in the situation where this should be done with constructor injection.
In other words I want to inject dependency to no parameter constructor. Something like that
class MyBaseException()
{
private IWorkingContext workingContext;
public MyBaseException()
{
this.workingContext = workingContext;
}
}
And yes, I know that normally I need to do it like this:
public MyBaseException(IWorkingContext workingContext)
But want this constructor MyBaseException(IWorkingContext workingContext) to be invoked without parameteres so in the end I could use my child class like MyCustomException() and have the workingContext wrapped in it.
My Windsor registration:
container.Register(Component.For<IWorkingContext>().ImplementedBy<WorkingContext>().LifeStyle.PerWebRequest)
I've tried this approach:
var containerAccessor = HttpContext.Current.ApplicationInstance as IContainerAccessor;
var container = containerAccessor.Container;
var operationContext = container.Resolve<IWorkingContext>();
but it doesn't work (new object is created by Windsor).
The moment you
new
up an exception - or any class for that matter - it is not managed by your IOC container, so it simply can't help you enrich your exception class.There are a couple of things you can do, however, some of them of questionable quality:
Use a factory method/class - registered in your IOC container with a dependency on
IWorkingContext
- which will actually give you an instance of your exception to throw up the stack. This still means that your exception would have a constructor accepting in a dependency, but the class throwing the exception doesn't know or need to know this. (I would recommend this approach)A dedicated class, living on the periphery of your domain, designed to catch and subsequently enrich any exceptions bubbling up the stack. This is risky for several reasons:
Personally, I'd look at 2 as the most viable option, but it can grow out of control quickly if you have a lot of different custom exceptions throughout your application. I would always look at 4, regardless of which option you go for because sometimes the problem you're trying to solve is the wrong problem.