4

I can add a named instance to structuremap like this:

For<IFoo>().Add<Foo>().Named("FooOne");

which I can then get with:

ObjectFactory.GetNamedInstance<IFoo>("FooOne");

and I can pass parameters at runtime by registering like this:

For<IFoo>().Add<Foo>().Ctor<string>("someParam");

and get an instance like this:

ObjectFactory.With("someParam").EqualTo("blah").GetInstance<IFoo>();

All fine. But I want to have a named instance and pass it a parameter. So I'm registering like this:

For<IFoo>().Add<Foo>().Named("FooOne").Ctor<string>("someParam");

But I can't work out the syntax for getting a named instance AND passing it the parameter at runtime?? I'm trying to do something like:

ObjectFactory.With("someParam").EqualTo("blah").GetNamedInstance<IFoo>("FooOne");

But structuremap doesn't give me the option to GetNamedInstance after adding the parameter. Where am I going wrong?

Alternative approach suggestions would also be good. Essentially what I'm trying to do is register a concrete type for each element of an enum, and use the enum item to name it and retrieve it by name. But I need to be able to pass a parameter to the constructor at runtime.

Thanks in advance.

soupy1976
  • 2,787
  • 2
  • 26
  • 34

2 Answers2

3

StructureMap doesn't provide an API for doing that.

You can use an abstract factory. There are lot's of examples that can be found here on Stack Overflow.

A few of them are this one and that one.

Community
  • 1
  • 1
Martijn B
  • 4,065
  • 2
  • 29
  • 41
1

You can use

var args = new ExplicitArguments();
args.SetArg("someParam", blah);
ObjectFactory.Container.GetInstance<IFoo>(args, "FooOne");