c# - CaSTLe Windsor 中的条件解析

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

我正在开发 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/

相关文章:

c# - Azure 引用本地路径时出错

c# - asp.net mvc View 中如何显示数据库记录

c# - 从下拉列表中传入多个值

c# - 如何将复杂的对象集合传递给mvc中的 Controller

c# - 如何根据一个 LINQ 查询的结果过滤另一个查询的结果?

c# - 放大或缩小时如何使 Canvas 区域在 ScrollViewer 中居中,而不是所有内容都可以显示在查看窗口中

c# - ASP.NET MVC 绑定(bind)十进制值

c# - 违反 PRIMARY KEY 约束 : Cannot insert duplicate key in object

c# - 是否存在使用不会处理对象的情况?

c# - 使用 TeamCity 构建解决方案的问题(可能是 nuget 问题)