使用WindsorControllerFactory解析MVC控制器

时间:2011-12-12 11:38:38

标签: model-view-controller inversion-of-control castle-windsor ioc-container

我是温莎的新手,所以

这是我的安装人员:

public class ControllersInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(FindControllers().Configure(ConfigureControllers()));
    }

    private ConfigureDelegate ConfigureControllers()
    {
        return c => c.LifeStyle.Transient;
    }

    private BasedOnDescriptor FindControllers()
    {
        return AllTypes.FromThisAssembly()
            .BasedOn<IController>()
            .If(Component.IsInSameNamespaceAs<HomeController>())
            .If(t => t.Name.EndsWith("Controller"));
    }
}

工厂:

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)
    {
        try
        {
            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);
        }
        catch(Exception ex)
        {
            return null;
        }
    }

}

从Controller继承的所有控制器都得到了很好的解决。但是当我尝试实例化这样的东西时:

public class ArticleController : RestController<Article>
{
    protected override JsonResult Create(Article item)
    {
        ...
    }
}

RestController也继承自Controller

它扔了 IControllerFactory'TheStorage.Web.Factories.WindsorControllerFactory'未返回名称为“Article”的控制器

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您收到的错误是由于您在工厂投放的try / catch。你不应该这样做。

现在,最有可能发生的事情是,您的容器无法解析您的控制器,可能是因为它具有无法解析的依赖关系,或者它没有被注册(可能您将它放在错误的命名空间中)?

一旦你让它失败,温莎会告诉你究竟是什么问题。