我有以下代码:
var container = new Container();
//car
container.Configure(
x => x.For<ICar>().Use<Honda>());
//engines
container.Configure(x => x.For<IEngine>().Use<V8Engine>().Named("V8"));
container.Configure(x => x.For<IEngine>().Use<V12Engine>().Named("V12"));
var car = container.GetInstance<ICar>();
Console.WriteLine(car.Name());
IEngine
是ICar
具体实现使用的接口,并在构造函数中注入。
现在默认情况下,StructureMap将使用V12Engine
,但我希望它使用V8Engine
,我该如何实现这种情况?
答案 0 :(得分:2)
我找到了解决这个问题的方法,如果有其他人需要,我会在下面给出:
解决方案1:
var car = container.With(container.GetInstance<IEngine>("V8")).GetInstance<ICar>();
解决方案2:
var engine = new V8Engine();
var car = container.With<IEngine>(engine).GetInstance<ICar>();
解决方案3 :(如果您有很多依赖项)
var engine = new V8Engine();
var eArgs = new ExplicitArguments();
eArgs.Set<IEngine>(engine);
var car = container.GetInstance<ICar>(eArgs);
可在此处找到更详细的说明:http://structuremap.github.io/resolving/passing-arguments-at-runtime/