Cannot add Controllers to Castle.Windsor in ASP.NE

2020-06-30 04:31发布

问题:

Given the following setup, I have three assemblies.

Web (ASP.NET MVC 3.0 RC1)

Models

Persistence (Fluent NHibernate, Castle.Windsor)

This is my ControllerInstaller.

using System;
using System.Web.Mvc;

using Castle;
using Castle.Windsor;

using Castle.MicroKernel;
using Castle.MicroKernel.SubSystems;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;

namespace Persistence.Installers
{
    public class ControllerInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(
            AllTypes
                .FromAssembly(System.Reflection.Assembly.GetExecutingAssembly())
                .BasedOn<IController>()
                .Configure(c => c.Named(
                    c.Implementation.Name.ToLowerInvariant()).LifeStyle.Transient));
        }
    }
}

This is my ControllerFactory...

    using System;
    using System.Web;
    using System.Web.Mvc;
    
    namespace Persistence.Containers
    {
        /// <summary>
        /// Utilize Castle.Windsor to provide Dependency Injection for the Controller Factory
        /// </summary>
        public class WindsorControllerFactory : DefaultControllerFactory
        {
            private readonly Castle.Windsor.IWindsorContainer container;
    
            public WindsorControllerFactory()
            {
                container = WindsorContainerFactory.Current();
            }
    
            protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
            {
                return (IController)container.Resolve(controllerType);
            }
        }
    }

This is my Application_Start in the global.asax file..

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

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        // Register the Windsor Container
        ControllerBuilder.Current
            .SetControllerFactory(typeof(Persistence.Containers.WindsorControllerFactory));
    }

I am getting the error

No component for supporting the service Project.Web.Controllers.HomeController was found

at the GetControllerInstance.

So , I'm not really sure what I am doing wrong, and why I cannot get the Controllers registered.

回答1:

Your Castle Windsor setup code all belongs in your Web project. It is nothing to do with Persistence.

This is causing the problem because your ControllerInstaller is trying to register the controllers in the Persistence assembly rather than the Web assembly with the following code:

System.Reflection.Assembly.GetExecutingAssembly().

So move the IoC code to the Web project and it will find your controllers.