Structuremap - how can I get a named instance and

2019-04-10 07:59发布

问题:

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.

回答1:

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.



回答2:

You can use

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