tags:

views:

64

answers:

2

Out of interest: In ASP.net MVC you can roll your own ControllerFactory. I just wonder why you would want to do that? I see dependency injection mentioned which makes sense to roll your own ControllerFactory, but then again I am not sure why I would want to use DI on the Controllers.

Swapping out the Model makes perfect sense, swapping out the Views also has some obvious uses, but I'm not sure if I could think of any use-case for swapping out Controllers that does not result in an architecture nightmare.

Any examples?

+3  A: 

We do it for two reasons:

  1. Dependency injection. This is how we swap out the model for unit testing controllers. The controller has a service interface reference, from which it gets the model types it needs.
  2. Overriding the default "ControllerName + Controller" convention. We don't actually have a specific controller type for every controller the end user sees. In some cases we generate controllers dynamically. The controller factory handles these cases.

That said, this is all just a few lines of code; most of the real work is done by the inherited controller factory from the framework. So the answer to your question is partially, "not much."

Craig Stuntz
+1  A: 

Hey,

I Craig answered the "Use Case" part of your question and he's correct it's very easy to create your own Controller factory.

Here's my example of how to do it using Ninject as the Ioc Container. Perhaps it will help someone else. I also hope it answers the "Example" part of your question.

http://www.craftyfella.com/2010/02/creating-aspnet-mvc-2-controller.html

CraftyFella