C# Castle Windsor-基于类名解析依赖项
假设我已使用以下代码从文件夹中注册了多个外部依赖项:C# Castle Windsor-基于类名解析依赖项,c#,inversion-of-control,castle-windsor,containers,C#,Inversion Of Control,Castle Windsor,Containers,假设我已使用以下代码从文件夹中注册了多个外部依赖项: container.Register(Types.FromAssemblyInDirectory(new AssemblyFilter("")) .Where(a = >a.IsSubclassOf(typeof(MyPlugin)))); 上面的代码运行良好,我能够看到容器中继承的所有依赖项MyPlugin。假设我在容器中有继承自MyPluginA的类MyPluginA和MyPluginB,我想检索MyPluginA。我该怎
container.Register(Types.FromAssemblyInDirectory(new AssemblyFilter(""))
.Where(a = >a.IsSubclassOf(typeof(MyPlugin))));
上面的代码运行良好,我能够看到容器中继承的所有依赖项MyPlugin
。假设我在容器中有继承自MyPluginA
的类MyPluginA
和MyPluginB
,我想检索MyPluginA
。我该怎么做呢
谢谢通常的方法是使用名称注册每个实现,并使用名称解析它们。我过去就是这样做的 要在安装程序中注册插件,请执行以下操作:
container.Register(
Component.For<MyPlugin>.Named(MyPluginA.ID).ImplementedBy<MyPluginA>());
定义一个组件选择器,可以选择作为构造函数中第一个参数提供的插件ID:
public class PluginFactorySelector : DefaultTypedFactoryComponentSelector
{
protected override string GetComponentName(MethodInfo method, object[] arguments)
{
return (method.Name.EndsWith("ById") && arguments.Length >= 1 && arguments[0] is string)
? (string) arguments[0]
: base.GetComponentName(method, arguments);
}
}
最后,在应用程序的安装程序中连接所有内容
container.Register(
Component.For<PluginFactorySelector, ITypedFactoryComponentSelector>().LifestyleSingleton(),
Component.For<IPluginFactory>().AsFactory(c => c.SelectedWith<PluginFactorySelector>()));
container.Register(
Component.For().LifestyleSingleton(),
Component.For().AsFactory(c=>c.SelectedWith());
container.Register(
Component.For<PluginFactorySelector, ITypedFactoryComponentSelector>().LifestyleSingleton(),
Component.For<IPluginFactory>().AsFactory(c => c.SelectedWith<PluginFactorySelector>()));