我有一种情况,我创建了一个工厂方法来创建一个对象。但是,该对象具有需要在创建对象之前执行的样板代码。修复这部分设计超出了这个问题的范围。
此外,当创建对象时,屏幕上的状态显示也会更新。这要求在创建此对象之前先实例化此状态显示并使其可见,并且应用程序处于运行状态。它作为依赖项传递给工厂。
我正在使用 StructureMap v3.1.4.143。
所以,这就是我在正常世界中(IoC 之前)要做的事情:
GraphicsInterface GetGraphics()
{
VideoDevicesList.GetVideoDevices();
// Some logic here to determine the device to use...
// Also, a status display is being updated to inform the user of
// what's happening at this point.
VideoDevice device = ...;
// The second parameter is a constant value, but the first is not.
return new GraphicsInterface(device, featureLevels.FL5);
}
看起来很简单,但理想情况下我希望能够通过注入传递该图形对象,因为很多地方都需要它。
因此,在结构图中,我创建了一个工厂函数来执行上述操作。然而这却给我带来悲伤。
new Container(obj =>
{
// This is passed to the object that depends on it.
// I've just left it out for brevity.
// It'd go something like: _graphics = _getGraphicsFactory();
// where _getGraphicsFactory is the factory function below.
For<Func<IStatusDisplay, GraphicsInterface>>
.Use<Func<IStatusDisplay, GraphicsInterface>>(GetGraphics);
}
只有这给了我一个有关 GraphicsInterface 未注册的错误。没关系,我应该能够注册 GraphicsInterface 对象。除了我无法注册 GraphicsInterface 因为构造函数需要两个参数,其中之一must在创建对象之前进行查询,并且只能通过上面的 GetVideoDevices 方法进行设置,当我调用 _getGraphicsFactory() 时,StructureMap 似乎尝试为我创建对象(这很奇怪,我希望它执行我的函数创建对象)。
我什至尝试在 GetVideoDevices 方法中像这样调用 GetInstance:
_container
.With<VideoDevice>(device)
.With<FeatureLevel>(FeatureLevel.FL5)
.GetInstance<Graphics>();
但没有骰子...
那么,有人知道我如何让它发挥作用吗?