【发布时间】:2013-03-15 00:02:22
【问题描述】:
我正在重构我们的应用程序以包含依赖注入(通过构造函数注入)并且遇到了一个棘手的极端情况:
我们目前有ImageViewer 对象,在实例化时会在程序集中搜索ImageViewerPlugin(抽象基类)实例,并使用反射实例化它们。这是在ImageViewer 的构造函数中使用类似于以下的方法(在所有具体插件类型的循环中调用)完成的:
private ImageViewerPlugin LoadPlugin(Type concretePluginType)
{
var pluginConstructor = concretePluginType.GetConstructor(
BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public,
null,
new[] { typeof(ImageViewer) },
null);
return (ImageViewerPlugin) pluginConstructor.Invoke(
new object[] { constructorParameter });
}
ImageViewerPlugin 类大致如下:
internal ImageViewerPlugin
{
protected ImageViewer _viewer;
protected ImageViewerPlugin(ImageViewer viewer)
{
_viewer = viewer;
}
}
具体的实现大致如下:
internal AnImageViewerPlugin
{
public AnImageViewerPlugin(ImageViewer viewer) : base(viewer)
{
}
}
每个ImageViewer 实例都有自己的ImageViewerPlugin 实例集合。
现在应用程序被重构为使用 DI 容器和构造函数注入,我发现这些插件具有需要由 DI 容器解决的依赖项(以前通过使用全局静态类隐藏),但是如果不使用服务定位器(反模式),我不确定如何做到这一点。
最明智的解决方案似乎是使用 DI 创建这些插件实例。这将允许我添加额外的构造函数参数,以通过构造函数注入注入它们所依赖的依赖项。但是如果我这样做了,如何在注入其余参数值的同时传递特定的viewer 参数值?
我认为ImageViewerPluginFactory 将有助于实现这一点,但看不到如何实现这样的工厂,因为每个插件可能具有不同的构造函数签名。
我该如何解决这种情况?还是我以完全错误的方式处理这个问题?
【问题讨论】:
标签: c# plugins dependency-injection simple-injector