[英]Conditional Resolve in Castle Windsor
我正在開發一個ASP.NET MVC 4 Web應用程序。 默認控制器工廠已被WindsorControllerFactory替換,如此處所示 。 這很有用,因為此應用程序中的控制器包含對幾個服務的引用,這些服務是使用Windsor注入實現的。 每個服務都有一個代理來包裝它。
因此,我們有以下情況:
它看起來像:
// This URL can be resolved at application startup
container.Register(Component.For<ITestService>()
.UsingFactoryMethod(() => ServiceFactory.CreateService<ITestService>(Settings.Default.ConfigurationProviderUrl))
.Named(MainServiceComponent)
.LifeStyle.Transient);
// The URL for this service can be configured during runtime. If it is null or empty it should not be resolved
container.Register(Component.For<ITestService>()
.UsingFactoryMethod(() => ServiceFactory.CreateService<ITestService>(SiteInformation.PublishUrl))
.Named(PublicationServiceComponent)
.LifeStyle.Transient);
// This proxy is necessary
container.Register(Component.For<IConfigurationProxy>()
.ImplementedBy<ConfigurationProxyWebService>()
.ServiceOverrides(ServiceOverride.ForKey(typeof(ITestService)).Eq(MainServiceComponent))
.LifeStyle.Transient);
// This proxy should be created only if SiteInformation.PublishUrl is different from empty or null
container.Register(Component.For<IConfigurationPublicationProxy>()
.ImplementedBy<ConfigurationPublicationProxyWebService>()
.ServiceOverrides(ServiceOverride.ForKey(typeof(ITestService)).Eq(PublicationServiceComponent))
.LifeStyle.Transient);
有沒有辦法讓Windsor在解決之前評估一個條件? 我知道它有條件注冊,但我還沒有找到一種方法來進行條件解決...提前謝謝!
我不是返回一個null
引用(正如你在評論中所說的那樣),而是返回一個null服務實現 。 換句話說,實現是無操作或僅僅是直通。 這樣,使用該服務的類不需要添加它實際上不應該知道的任何邏輯(即服務在給定情況下是否有效)。
為此,您可以使用UsingFactoryMethod
功能來決定在運行時返回哪個服務。 進行首次注冊時,您需要有條件:
// The URL for this service can be configured during runtime.
// If it is null or empty it should not be resolved.
container.Register(Component.For<ITestService>()
.UsingFactoryMethod((kernel, context) =>
{
if (!string.IsNullOrEmpty(SiteInformation.PublishUrl))
return ServiceFactory.CreateService<ITestService>(
SiteInformation.PublishUrl));
return kernel.Resolve<INullTestService>();
})
.Named(PublicationServiceComponent)
.LifeStyle.Transient);
我不知道您的ITestService
接口是什么樣的,但我會從中派生出INullTestService
,並且實現盡可能少。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.