I user Autofac and wonder if it is possible to come around the DependencyResolutionException that is thrown if the instance that is returned by a registered type is null?
Consider the following example:
builder.Register( c => c.Resolve<HttpContextBase>().CurrentHandler as ITemplatePage
).InstancePerHttpRequest();
The example will return null if the current handler (for example the aspx-page that I am visiting) isn’t of type ITemplatePage, and Autofac will throw the DependencyResolutionException even if I use the ResolveOptional alternative like in this way:
container.ResolveOptional<ITemplatePage>();
Is there any way to come arond this and get an behaviour where Autofac returns null instead of thowing an exeption?
I have worked around this by adding a IsNull-proerty to ITemplatePage and always instanciate it, like this:
builder.Register( c =>
c.Resolve<HttpContextBase>().CurrentHandler as ITemplatePage
?? new TemplatePage(true)
).As<ITemplatePage>().InstancePerHttpRequest();
and then I can work with it in this way:
var templatePage = container.Resolve<ITemplatePage>();
if(!templatePage.IsNull){
// Do stuff
}
But I do not think that is an optimal solution to my problem.
Edit:
To catch the error is not an option since I use ITemplatePage in constructors of other types I resolve, and since I am using constructor injection to resolve these types I want them to return the instance created with the constructor without the ITemplatePage parameter rather than to crash as well.
The best way to do this is to register the service conditionally at the start of a web request, e.g. (pseudocode):
This way, you can simply make the
ITemplatePagean optional constructor parameter of components that can use it (ITemplatePage tp = null) or use property injection/ResolveOptional().Note there have been some reliability improvements around these kinds of delayed registrations in Autofac 2.5 so I recommend updating before using this approach.