Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Castle Windsor-基于类名解析依赖项_C#_Inversion Of Control_Castle Windsor_Containers - Fatal编程技术网

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>()));