2013-10-28 31 views
0

假設我已經註冊使用下面的代碼一批從文件夾中的外部依賴的:城堡溫莎 - 基於類的名稱解析相關

container.Register(Types.FromAssemblyInDirectory(new AssemblyFilter("")) 
    .Where(a = >a.IsSubclassOf(typeof(MyPlugin)))); 

上面的代碼工作正常,我能看到所有的依賴在容器中繼承MyPlugin。假設我在容器中繼承MyPlugin的類MyPluginAMyPluginB,我想檢索MyPluginA。我應該怎麼做呢?

感謝

回答

0

通常的方法是註冊一個名稱每個實現,並使用該名稱加以解決。這是我過去的做法。

要在其安裝程序註冊的插件:

container.Register(
    Component.For<MyPlugin>.Named(MyPluginA.ID).ImplementedBy<MyPluginA>()); 

ID可能是類的名稱,或任何唯一的字符串ID。爲了解決這個問題,你可以讓Windsor爲你實施一個可以接受ID的工廠。定義接口:

public interface IPluginFactory 
{ 
    MyPlugin CreatePluginById(String id); 
} 

定義組件選擇,可以選擇作爲一個構造函數的第一個參數提供的插件的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>()));