C# 在StructureMap中注册同一对象两次有什么好方法吗?

C# 在StructureMap中注册同一对象两次有什么好方法吗?,c#,structuremap,C#,Structuremap,我在使用StructureMap的.NET应用程序中包含了一些功能切换。我想注册功能切换有两个目的 在诊断页面上显示所有IFeatures的当前状态 在依赖给定的IFeature实现的服务构造函数中使用某些实例 这是我的设置。我想知道的是,我做得对吗?我有没有更好的办法 class HotNewFeature : IFeature { ... } class ServiceThatUsesFeature { public ServiceThatUsesFeature(HotNew

我在使用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>();
class HotNewFeature:IFeature{…}
使用功能的类服务
{
使用功能的公共服务(HotNewFeature HotNewFeature){…}
}
//类型注册表设置
For().Singleton().Use();
For().Singleton().Add(c=>c.GetInstance);
For().Singleton().Use());
//获取诊断页面上的所有实例:
IEnumerable features=ServiceLocator.Current.GetAllInstances();

我希望在诊断页面上,
功能
将在本例中包含一个带有单个元素的
IEnumerable
,HotNewFeature的实例使用
扫描
功能注册实现IFeature的所有类型。这将满足您的第一个需要,即在诊断页面上显示列表


如果服务需要特定的实现,它应该声明它需要的特定类型(
HotNewFeature
),而不是构造函数中的接口(
IFeature
)。在您的示例中,您已经正确地做到了这一点。此时,您不需要在StructureMap中执行更多操作。如果您从StructureMap请求用户功能的服务,并且它依赖于具体类(
HotNewFeature
),StructureMap将知道如何实例化该具体类。

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


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

请确切说明您希望GetAllInstances返回的实例。请确切说明您希望GetAllInstances返回的实例。