I’m working with the ASP.Net MVC 3 framework and I’m integrating dependency injection into the application. I’m trying to create a custom controller factory. The biggest issue I’m having at this moment is my implementation of IControllerFactory.CreateController gets passed requests for things like css, javascript, and other content files which subsequently causes it to throw an exception as the type for “Scripts/html5.js” doesn’t exist. The code was inherited to me, so save any criticism you may have as to the very haphazard state. Here is the implementation:
public virtual IController CreateController(RequestContext requestContext, string controllerName)
{
if (requestContext == null)
{
throw new ArgumentNullException("requestContext");
}
if (String.IsNullOrEmpty(controllerName))
{
throw new ArgumentException("Value cannot be null or empty", "controllerName");
}
this.RequestContext = requestContext;
try
{
return container.Resolve<IController>(controllerName.ToLower());
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
return innerFactory.CreateController(requestContext, controllerName);
}
}
I was able to solve this by inheriting from the
DefaultControllerFactoryinstead of implementing IControllerFactory in its entirety:Then I only needed to override the
GetControllerInstancemethod to hook in and return any instances from my Unity container: