在带有区域的MVC中使用依赖注入定位控制器

时间:2022-08-12 15:47:46

I am working on an MVC 5 application that utilizes Castle Windsor. I've separated my code using areas to make it more manageable. I have also updated my instantiated class of IWindorInstaller to include an extra method that will find the controllers from this new area.

我正在开发一个使用Castle Windsor的MVC 5应用程序。我已经使用区域分隔我的代码以使其更易于管理。我还更新了我的实例化的IWindorInstaller类,以包含一个额外的方法,它将从这个新区域中找到控制器。

My code looks like this:

我的代码如下所示:

public void Install(IWindsorContainer container, IConfigurationStore store)
{
    container.Register(FindStandardControllers());
    container.Register(FindAdminControllers());
}

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

private BasedOnDescriptor FindAdminControllers()
{
    return Classes.FromThisAssembly()
        .BasedOn<IController>()
        .If(Component.IsInSameNamespaceAs<AdminController>())
        .If(t => t.Name.EndsWith("Controller"))
        .LifestyleTransient();
}

All of this works, but is there a better way to tell Windsor to automagically pick up all the controllers from each new area?

所有这些都有效,但有没有更好的方法告诉温莎自动从每个新区域拿起所有控制器?

I'm especially concerned if I want to include similarly named controllers (eg: HomeController) in each area.

如果我想在每个区域中包含类似命名的控制器(例如:HomeController),我会特别担心。

1 个解决方案

#1


1  

Since all your controllers are inherited from IController you shouldn't specify namespace and suffix.

由于所有控制器都是从IController继承的,因此不应指定命名空间和后缀。

public void Install(IWindsorContainer container, IConfigurationStore store)
{
    container.Register(
        Classes.FromThisAssembly()
            .BasedOn<IController>()
            .LifestyleTransient()
    );
}

In case you have controllers with the same name they will be in different namespaces and Windsor will resolve them correctly.

如果您具有相同名称的控制器,它们将位于不同的名称空间中,Windsor将正确解析它们。

#1


1  

Since all your controllers are inherited from IController you shouldn't specify namespace and suffix.

由于所有控制器都是从IController继承的,因此不应指定命名空间和后缀。

public void Install(IWindsorContainer container, IConfigurationStore store)
{
    container.Register(
        Classes.FromThisAssembly()
            .BasedOn<IController>()
            .LifestyleTransient()
    );
}

In case you have controllers with the same name they will be in different namespaces and Windsor will resolve them correctly.

如果您具有相同名称的控制器,它们将位于不同的名称空间中,Windsor将正确解析它们。