MVC UrlHelper in SimpleInjector

Jan 26, 2013 at 1:37 PM
Edited Jan 26, 2013 at 1:39 PM

I want to create a class that requires a UrlHelper. The UrlHelper class takes an instance of System.Web.Routing.RequestContext in its constructor. I tried registering it like this:

 

container.RegisterPerWebRequest<RequestContext>(() => HttpContext.Current.Request.RequestContext);
container.RegisterPerWebRequest<UrlHelper>(() => new UrlHelper(container.GetInstance<RequestContext>()));

 

However, when I call container.Verify, I get this exception:

Request is not available in this context

[HttpException (0x80004005): Request is not available in this context]
   System.Web.HttpContext.get_Request() +9718452
   Daniel15.Web.Infrastructure.Ioc.<InitializeContainer>b__1() in C:\Users\Daniel\Documents\Visual Studio 2010\Projects\dan.cx_dotnet\Daniel15.Web\Infrastructure\Ioc.cs:70
   lambda_method(Closure ) +31
   SimpleInjector.Integration.Web.PerWebRequestInstanceCreator`1.CreateInstance(HttpContext context) +21
   SimpleInjector.Integration.Web.PerWebRequestInstanceCreator`1.GetInstance() +170
   lambda_method(Closure ) +72
   SimpleInjector.InstanceProducers.InstanceProducer.GetInstance() +72

[ActivationException: The registered delegate for type UrlHelper threw an exception. Request is not available in this context]
   SimpleInjector.InstanceProducers.InstanceProducer.ThrowErrorWhileTryingToGetInstanceOfType(Exception innerException) +123
   SimpleInjector.InstanceProducers.InstanceProducer.GetInstance() +114
   SimpleInjector.Helpers.Verify(IInstanceProducer instanceProducer, Type serviceType) +28

[InvalidOperationException: The configuration is invalid. Creating the instance for type UrlHelper failed. The registered delegate for type UrlHelper threw an exception. Request is not available in this context]
   SimpleInjector.Helpers.Verify(IInstanceProducer instanceProducer, Type serviceType) +79
   SimpleInjector.Container.ValidateRegistrations() +124
   SimpleInjector.Container.Verify() +54
   Daniel15.Web.Infrastructure.Ioc.Initialize() in C:\Users\Daniel\Documents\Visual Studio 2010\Projects\dan.cx_dotnet\Daniel15.Web\Infrastructure\Ioc.cs:46
   Daniel15.Web.MvcApplication.Application_Start() in C:\Users\Daniel\Documents\Visual Studio 2010\Projects\dan.cx_dotnet\Daniel15.Web\Global.asax.cs:16

I assume this is because it's not in a HTTP request.

What is the best way to handle something like this?

Coordinator
Jan 26, 2013 at 2:08 PM

Best is to return a Null Object (or mock object) in case Request.Current is null. This ensures that the registrations keeps valid and can be verified.

Marked as answer by dot_NET_Junkie on 11/4/2013 at 2:05 AM