views:

118

answers:

1

Hello,

I am creating an application using ASP.NET MVC (2) and Spring.NET.

Since most of my Controller implementations just implement the similar CRUD operations, I would like to just create a single Generic controller, as explained here:

http://stackoverflow.com/questions/848904/in-asp-net-mvc-is-it-possible-to-make-a-generic-controller

However, the above example doesn't take DI frameworks into consideration.

What I'm thinking is to create this (warning: this is an ugly mass of code I need help with):

public SpringGenericControllerFactory : DefaultControllerFactory {

    public IController CreateController(RequestContext requestContext, string controllerName) {

        // Determine the controller type to return
        Type controllerType = Type.GetType("MyController").MakeGenericType(Type.GetType(controllerName));

        // Return the controller
        return Activator.CreateInstance(controllerType) as IController;

    }
}

The entries in objects.xml would look something like this:

<object id="controllerFactory" type="Application.Controllers.SpringGenericControllerFactory" />

<object id="DepartmentController" factory-method="CreateController" factory-object="controllerFactory" />

Can anyone pick through this and offer advice?

A: 

Two things:

  • The controllerName argument will actually come through as 'Department' not 'DepartmentController'. You either need to handle this or adjust the name in your objects.xml

  • Make sure you fall back to the default implementation if the context does not return a controller. In this instance you should fall back to the base classes implementation.

JHappoldt