如何添加依赖到现有的温莎城堡注册
本文关键字:注册 城堡 何添加 添加 依赖 | 更新日期: 2023-09-27 17:53:22
我们通过BasedOn查询向Castle注册了一堆控制器。我们希望在其中一个控制器上添加额外的配置依赖项。我们可以在所有控制器中注册该参数。下面的代码是我们如何解决这个问题,但我想知道是否有一个更优雅/内置的解决方案。
public class ControllersInstaller : IWindsorInstaller
{
private readonly IAppConfig _appConfig = new AppConfig();
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(FindControllers().Configure(ConfigureComponentRegistration).LifestyleTransient());
container.Register(Component.For<BarController>()
.LifestyleTransient()
.DependsOn(Dependency.OnValue("faxNumber",
_appConfig.GetAppSetting<string>("FaxNumber"))));
}
private void ConfigureComponentRegistration(ComponentRegistration obj)
{
obj.LifestyleTransient();
}
private BasedOnDescriptor FindControllers()
{
return Classes.FromThisAssembly()
.BasedOn<IController>()
.If(Component.IsInSameNamespaceAs<FooController>(true))
.If(t => t.Name.EndsWith("Controller") && t.Name != "BarController")
.LifestyleTransient();
}
}
我建议您简单地用一个更具体的版本覆盖现有的注册,该版本对_appConfig有必要的依赖。因此,您不必使用此过滤器:
t.Name != "BarController"
查看我的答案在这里,如何覆盖现有的组件:https://stackoverflow.com/a/37832194/644891
完全可以,只要使用ConfigureFor<>
方法。
container.Register(FindAllControllers()
.ConfigureFor<BarController>(x =>
x.DependsOn(Dependency.OnAppSettingsValue("faxNumber"))
)
);
作为我的旁注,我不确定为什么你的例子指定生命周期三次。做一次就够了。