【问题标题】:Conditional Resolve in Castle Windsor温莎城堡中的条件解决
【发布时间】:2015-01-19 03:55:28
【问题描述】:

我正在开发一个 ASP.NET MVC 4 Web 应用程序。默认控制器工厂已按照建议 here 替换为 WindsorControllerFactory。这很有用,因为此应用程序中的控制器包含对几个服务的引用,这些服务是使用 Windsor 注入实例化的。每个服务都有一个代理来包装它。

因此,我们有以下情况:

  • 在 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,那么我们可以稍后检查服务是否已经创建。

标签: c# asp.net-mvc asp.net-mvc-4 castle-windsor


【解决方案1】:

我不会返回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 接口是什么样的,但我会让INullTestService 派生自它,并且实现尽可能少。

【讨论】:

  • 谢谢!这是要走的路。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多