structuremap确实返回命名实例而不是默认实例

时间:2011-07-21 08:28:38

标签: structuremap named-instance

正如标题所说,当我还配置了命名实例时,structuremap不会返回默认实例。

这是我的类型注册:

/// <summary>
  /// Initializes a new instance of the <see cref="CommandProcessingTypeRegistry"/> class.
  /// </summary>
  public CommandProcessingTypeRegistry()
  {
     For<ICommandProcessor>().Singleton().Use<CommandCoordinator>();

     For<ICommandProcessor>().Singleton().Use<SystemCommandSwitch>().Named(typeof(SystemCommandSwitch).FullName);
     For<ICommandProcessor>().Singleton().Use<TelephonyCommandSwitch>().Named(typeof(TelephonyCommandSwitch).FullName);
     For<ICommandProcessor>().Singleton().Use<AudioCommandSwitch>().Named(typeof(AudioCommandSwitch).FullName);
     For<ICommandProcessor>().Singleton().Use<TetraCommandSwitch>().Named(typeof(TetraCommandSwitch).FullName);
     For<ICommandProcessor>().Singleton().Use<RadioCommandSwitch>().Named(typeof(RadioCommandSwitch).FullName);
     For<ICommandProcessor>().Singleton().Use<SnapshotCommandSwitch>().Named(typeof(SnapshotCommandSwitch).FullName);
     For<ICommandProcessor>().Singleton().Use<TakeNextCommandSwitch>().Named(typeof(TakeNextCommandSwitch).FullName);
  }

这就是我请求实例的方式:

_commandProcessor = _container.GetInstance<ICommandProcessor>(); // _container is the structuremap IContainer instance

我希望上面的行返回 CommandCoordinator 实例,而是返回 TakeNextCommandSwitch 实例。 我在这做错了什么?

1 个答案:

答案 0 :(得分:5)

您需要对命名实例使用Add而不是Use:

For<ICommandProcessor>().Singleton().Add<TelephonyCommandSwitch>().Named(typeof(TelephonyCommandSwitch).FullName);