我正在开发 ASP.NET MVC 4 网络应用程序。默认 Controller 工厂已按照建议替换为 WindsorControllerFactory here .这很有用,因为此应用程序中的 Controller 包含对几个服务的引用,这些服务是使用 Windsor 注入(inject)实例化的。每个服务都有一个代理来包装它。
因此,我们有以下情况:
- 注册到 CaSTLe 的两个组件(一个服务和一个代理)
- 其中一个被构建为另一个的依赖
它看起来像:
// 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);
有没有办法让温莎在解决之前评估条件?我知道它有条件注册,但我还没有找到进行条件解析的方法...在此先感谢您!
最佳答案
我不会返回一个 null
引用(如您在评论中所说),而是返回一个 null service implementation。 .换句话说,一个无操作或只是直通的实现。这样,使用该服务的类就不需要添加它实际上不应该知道的任何逻辑(即该服务在给定情况下是否有效使用)。
为此,您只需使用 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
接口(interface)是什么样的,但我会让 INullTestService
从它派生,并且实现尽可能少。
关于c# - CaSTLe Windsor 中的条件解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27961204/