我觉得我正在尝试完成一些不完全是“StructureMap 方式”的事情,或者可能是,但我只是不知道该怎么做。我希望有人可以帮助我:
我正在编写一个插件,该插件需要一个Execute
方法来传递IServiceProvider
(由运行我的插件的应用程序提供)。
目前,我的代码如下所示:
public void Execute(IServiceProvider serviceProvider)
{
//The serviceProvider is used to extract references to other objects it supplies:
this.Context = serviceProvider.GetService<IPluginExecutionContext>();
//This could go more than one level deep:
this.Acme = this.Context.Acme;
//Do something with this.Context and this.Acme here...
}
这对于在生产中运行时很好。但是,当我对这个插件进行单元测试时,我希望能够使用 StructureMap 插入我的 IPluginExecutionContext 或 Acme 的模拟版本。
现在,我知道如何让 StructureMap 为特定接口注册一个具体类型:
ObjectFactory.Initialize(x =>
{
x.For<IPluginExecutionContext>()
.Use<MockedPluginExecutionContext>();
});
但是,如果已配置,我如何让我的 Execute 实现使用此 MockedPluginExecutionContext ,或者serviceProvider.GetService<IPluginExecutionContext>()
如果未配置则使用返回的值?