Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc put controllers into a separate project

Tags:

asp.net-mvc

I'm just learning asp.net mvc and I'm trying to figure out how to move my controllers into a separate project. Typically when I have designed asp.net web apps before, I created one project for my models, another for my logic, and then there was the web.

Now that I'm learning asp.net mvc I was hoping to follow a similar pattern and put the models and controllers each into their own separate projects, and just leave the views/scripts/css in the web. The models part was easy, but what I don't understand is how to make my controllers in a separate project be "found". Also, I would like to know if this is advisable. Thanks!

like image 480
Aaron Palmer Avatar asked Dec 30 '08 20:12

Aaron Palmer


People also ask

Should you split your ASP NET MVC project into multiple projects?

It shouldn't! That's why it's designed in a modular way. In most web applications out there, we version and deploy all these assemblies (Web, BLL and DAL) together. So, separating a project into 3 projects does not add any values.

Can we have multiple controllers in MVC?

In Spring MVC, we can create multiple controllers at a time. It is required to map each controller class with @Controller annotation.

How do I move from one controller to another in MVC?

In this blog you will learn how to Redirect from One Controller Action to Another. Step1: Create an ASP.net MVC project. Choose ASP.Net MVC project from template and Press Next, then name the empty project as RoutingExample and click ok. Step 2: Add two controllers.


1 Answers

First of all, it is certainly a good idea to put your model into a separate project. As you've discovered, this is trivial.

Regarding Controllers and Views, I don't see any obvious advantage to separating them for most basic projects, although you may have a particular need to do so in a particular application.

If you do choose to do this, then you will need to tell the framework how to find your controllers. The basic way to do this is by supplying your own ControllerFactory. You can take a look at the source code for the DefaultControllerFactory to get an idea for how this is done. Subtyping this class and overriding the GetControllerType(string controllerName) method may be enough to accomplish what you're asking.

Once you've created your own custom ControllerFactory, you add the following line to Application_Start in global.asax to tell the framework where to find it:

ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory()); 

Update: Read this post and the posts it links to for more info. See also Phil Haack's comment on that post about:

ControllerBuilder.Current.DefaultNamespaces.Add(     "ExternalAssembly.Controllers"); 

...which is not a complete solution, but possibly good enough for simple cases.

like image 160
Craig Stuntz Avatar answered Sep 28 '22 08:09

Craig Stuntz