1

我在使用 StructureMap 的 .NET 应用程序中包含了一些功能切换。我想注册功能切换有两个目的。

  • 在诊断页面上显示所有 的当前状态。IFeatures
  • 在依赖给定IFeature实现的服务的构造函数中使用某些实例

这是我的设置。我想知道的是,我这样做对吗?有没有更好的方法可以做到这一点?

class HotNewFeature : IFeature { ... }

class ServiceThatUsesFeature 
{
    public ServiceThatUsesFeature(HotNewFeature hotNewFeature) { ... }
}

// Type registry setup
For<HotNewFeature>().Singleton().Use<HotNewFeature>();
For<IFeature>().Singleton().Add(c => c.GetInstance<HotNewFeature>);
For<ServiceThatUsesFeature>().Singleton().Use<ServiceThatUsesFeature>());

// Get all instances on the diagnostics page:
IEnumerable<IFeature> features = ServiceLocator.Current.GetAllInstances<IFeature>();

我希望在诊断页面上,features在这种情况下会包含一个IEnumerable带有单个元素的实例,即HotNewFeature.

4

1 回答 1

1

使用该Scan功能注册所有实现 IFeature 的类型。这将满足您的第一个需求,即在“诊断”页面上显示列表。

如果一个服务需要一个特定的实现,它应该在构造函数中声明它需要的特定类型(HotNewFeature)而不是接口(IFeature)。你在你的例子中正确地做到了这一点。此时,您无需在 StructureMap 中执行任何其他操作。如果您ServiceThatUsersFeature从 StructureMap 请求,并且它依赖于具体类 ( HotNewFeature),则 StructureMap 将知道如何实例化该具体类。

于 2013-01-10T18:14:47.773 回答