Search code examples
structuremapnamed-instance

structuremap does return named instance instead of default one


As the title says, structuremap does not return the default instance when i have also configured named instances.

Here is my type registration:

/// <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);
  }

And this is how i request the instance:

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

I would like that the above line returns me the CommandCoordinator instance but instead the TakeNextCommandSwitch instance is returned. What am i doing wrong here?


Solution

  • You need to use Add instead of Use for the named instances:

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