如何使用Castle Windsor与mvc Web应用程序不同的程序集?

时间:2015-01-07 19:57:25

标签: c# asp.net-mvc castle-windsor

我被困住了。我想在不同的类库中配置Castle Windsor,我配置,构建很好,没有错误,确定......但是我在运行时遇到异常。

  

Castle.MicroKernel.ComponentNotFoundException:找不到支持App.Web.UI.Controllers.HomeController服务的组件

当我将配置文件返回到同一个程序集(App.Web.UI)时,我在运行时没有得到任何异常,工作正常。

我尝试了很多方法,但我做不到。除了FromThisAssembly之外还有另一种绑定方法吗?还是解决方案?

Castle Windsor配置在这里:

namespace App.Infrastructure.Configurations
{
    public class WindsorControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel _kernel;

        public WindsorControllerFactory(IKernel kernel)
        {
            _kernel = kernel;
        }

        public override void ReleaseController(IController controller)
        {
            _kernel.ReleaseComponent(controller);
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
            }

            return (IController)_kernel.Resolve(controllerType);
        }
    }

    public class ControllersInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(Classes.FromThisAssembly().BasedOn<IController>().Unless(x => x.Name == "BaseController").LifestyleTransient());
        }
    }

    public class ServiceInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(
                Component.For(typeof (IRepository<>)).ImplementedBy(typeof (Repository<>)).LifestyleTransient(),
                Component.For<IUserService>().ImplementedBy<UserService>().LifestylePerWebRequest(),
                Component.For<IFormsAuthenticationService>().ImplementedBy<FormsAuthenticationService>().LifestylePerWebRequest(),
                Component.For<ILoggingService>().ImplementedBy<LoggingService>().LifestyleTransient(),
                Component.For<IFeedbackService>().ImplementedBy<FeedbackService>().LifestylePerWebRequest()
                ); 
        }
    }
}

1 个答案:

答案 0 :(得分:2)

在您的代码中,Classes.FromThisAssembly()引用包含Windsor内容的程序集 - 而不是您的Web应用程序。尝试告诉Windsor注册特定组件的组件。这应该有效:

Classes.FromAssembly(Assembly.GetEntryAssembly())

条目程序集应该是运行MVC代码的AppDomain。