Sunday, August 8, 2010

ASP.NET MVC 2 & StructureMap Error - ASP.NET MVC 2 - GetControllerInstance(System.Type)': no suitable method found to override - OH NO!

Don't you just wish that when you port your applications from ASP.NET MVC 1 to ASP.NET MVC 2 and beyond that things just worked? If it did, I guess it would put some of us out of work. It is always nice to know that thanks to these updates and the technologies we employ to make our lives easier, we will always have jobs.

StructureMap and ASP.NET MVC 2 gave me a nice little error that you and others might run across. The solution is quick and easy - unless you don't know it (LOL). While moving one of my applications from MVC 1 to MVC 2, I came across the StructureMap error. Here is the offending StructureMap code I used in ASP.NET MVC 1.

CODE THAT DOES NOT WORK IN ASP.NET MVC 2
protected override IController GetControllerInstance(Type controllerType)
{
if (controllerType == null) return null;
try
{
return (IController)ObjectFactory.GetInstance(controllerType);
}
catch (StructureMapException)
{
System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
throw;
}
}

It looks like it should work right? Well it did work, but guess what? Times have changed....well StructureMap has changed. So now the code should look like the following:

CODE THAT WILL WORK IN ASP.NET MVC 2
protected override IController GetControllerInstance(RequestContext requestContext,
Type controllerType)
{

if (controllerType == null)
return base.GetControllerInstance(requestContext, controllerType);

try
{
return (IController)ObjectFactory.GetInstance(controllerType);
}
catch (StructureMapException)
{
System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
throw;
}
}
And there you have it! Changes, changes, changes! I hope this puts a smile on your face or at least lets you get back to work.

Smooches,
Kila

No comments: