asp.net mvc put controllers into a separate project
While it is reasonable to create your own ControllerFactory, I found it more convenient to define all my Controllers in each project, but derive them from Controllers in my Shared project:
namespace MyProject1.Controllers
{
public class MyController : MySharedProject.Controllers.MyController
{
// nothing much to do here...
}
}
namespace MySharedProject.Controllers
{
public abstract class MyController : System.Web.Mvc.Controller
{
// all (or most) of my controller logic here...
}
}
This has the added benefit that you have a place to put your Controller logic that differs from project to project. Also, it is easier for other developers to quickly find your Controller logic because the Controllers exist in the standard place.
Regarding whether this is advisable, I think it absolutely is. I've created some common Account Management logic that I want to share between projects that otherwise have very different business logic. So I'm sharing my Account and Admin Controllers, but the other Controllers are specific to their respective projects.
- Add the Class Library for your mvc project.
In the class add the following code(For u'r Controller Code)
namespace ContactController { public class ContactController : Controller { public ActionResult Call() { ViewBag.Title = "Inside MyFirst Controller."; return View(); } }
}
On the mvc project view folder add the folder for Contact and create a Call.cshtml file.
Add the class library project reference into your main MVC project.
- Finally to refer contact controller namespace into Route Config.
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.