yey*_*man 4 c# asp.net-mvc castle-windsor asp.net-mvc-4
我正在开发 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);
Run Code Online (Sandbox Code Playgroud)
有什么方法可以让 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);
Run Code Online (Sandbox Code Playgroud)
我不知道你的ITestService界面是什么样的,但我会INullTestService从它派生,并且实现尽可能少做。
| 归档时间: |
|
| 查看次数: |
1870 次 |
| 最近记录: |