在设置IControllerFactory时,BetterCMS不会与Castle Windsor玩得很好

时间:2015-05-25 13:34:18

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

按照Windsor的标准MVC 5教程,我创建了一个WindsorControllerFactory

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));
    }

    if (controllerType != null && kernel.HasComponent(controllerType))
        return (IController)kernel.Resolve(controllerType);
    return base.GetControllerInstance(requestContext, controllerType);
}

我还想开始使用BetterCMS并且我已经获得了正确的Nuget包,并尝试在Global.asax初始化它:

__CmsHost = CmsContext.RegisterHost();

在调用之后,当我检查ControllerBuilder.Current.GetDefaultControllerFactory()时,我有BetterCMS的适当工厂。

但是要使用Windsor,我需要注册我自己的控制器工厂:

var controllerFactory = new WindsorControllerFactory(__Container.Kernel);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);

当然,现在当我尝试访问BetterCMS控制器时出现错误 - 它无法识别需要构建的控制器。

我已经尝试限制容器注册控制器的命名空间,但这并没有改变结果:

public void Install(IWindsorContainer container, IConfigurationStore store)
{
    container.Register(
        Classes.FromThisAssembly()
        .InNamespace("MyNamespace.Net.Web.Platform.Controllers", true)
        .LifestyleTransient());
}

我的意思是,它不像微软的SetControllerFactory会尊重我的温莎容器。

如果没有通过将BetterCMS工厂与我自己的工厂合并来创建工厂,我该怎么办才能让这两个工厂发挥得更好呢?

1 个答案:

答案 0 :(得分:0)

您可以使用decorator pattern,这样就不必将它们组合在一起。

public class ControllerFactoryDecorator : IControllerFactory
{
    public ControllerFactoryDecorator(
        IControllerFactory controllerFactory
        )
    {
        if (controllerFactory == null)
            throw new ArgumentNullException("controllerFactory");
        this.innerControllerFactory = controllerFactory;
    }

    private readonly IControllerFactory innerControllerFactory;

    // Implement IControllerFactory members and delegate each
    // call to the innerControllerFactory if it doesn't apply here.
}

然后只包装现有的IControllerFactory

// Setup the Controller Factory with a decorator
var currentFactory = ControllerBuilder.Current.GetControllerFactory();
ControllerBuilder.Current.SetControllerFactory(
    new ControllerFactoryDecorator(currentFactory));

查看完整示例here