views:

64

answers:

2

I need to find a way to put my MVC controllers into a different project from the MVC project.

I think I'm close. I've setup the Castle Windsor IoC container, and have my controllers in a different project. I think it's hanging up on the Web.Config. Is there a component I need to add? Here is the current exception I'm getting:

No component for supporting the service MySolution.Express.Controllers.HomeController was found

Here is my code:

Web.Config portion that pertains to Castle Windsor

<section name="castle"
             type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,
             Castle.Windsor" />
  </configSections>

   (....)
<castle>
    <components>

    </components>
  </castle>

Global.ascx

public static void RegisterRoutes(RouteCollection routes)
    {
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

      routes.MapRoute(
          "Default", // Route name
          "{controller}/{action}/{id}", // URL with parameters
          new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
      );

    }

    protected void Application_Start()
    {
      AreaRegistration.RegisterAllAreas();

      RegisterRoutes(RouteTable.Routes);
      ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory());
      ControllerBuilder.Current.DefaultNamespaces.Add("MyProject.Express.Controllers");
    }

WindsorControllerFactory.cs

 WindsorContainer container;

public WindsorControllerFactory()
{
  container = new WindsorContainer(
                   new XmlInterpreter(new ConfigResource("castle"))
               );
  var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                         where typeof(IController).IsAssignableFrom(t)
                         select t;
   foreach (Type t in controllerTypes)
     container.AddComponentWithLifestyle(t.FullName,t,
                                         LifestyleType.Transient); 
 }

protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
 {
   return (IController)container.Resolve(controllerType);
 }
  • Is there a component I need to add?
  • What else can I do to achieve this goal?
A: 

Okay, I got it. Here's the Web.Config component:

<component id="controller" type="MyProject.Express.Controllers.HomeController, MyProject.Express.Controllers" lifestyle="transient" />
jchapa
+2  A: 

The code you are using to register the controllers is looking at the executing assembly so it won't find the controllers. As you've found out one solution is to explicitly register the controllers.

Alternatively, if you use MvcContrib.Castle then you can replace the second line of code in your WindsorControllerFactory constructor with something like this to register all controllers from the controller assembly:

container.RegisterControllers(typeof(HomeController).Assembly);
Oenotria

related questions