Structuremap - how can I get a named instance and pass parameter at runtime?

痞子三分冷 提交于 2019-12-06 06:07:26

问题


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");


来源:https://stackoverflow.com/questions/19380933/structuremap-how-can-i-get-a-named-instance-and-pass-parameter-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!