2017-05-31 131 views
0

嗨我在XamarinMVVM項目中使用Ninject。我所試圖做的是基於一個枚舉類型綁定的具體實現:檢索提供程序中的自定義綁定參數Ninject

var foo = new Ninject.Parameters.Parameter("type", VMType, true); 
Kernel.Get<ICommonComponentVM>(foo); 

和供應商:

public class ICommonComponentVMProvider : Provider<ICommonComponentVM> 
{ 
    protected override ICommonComponentVM CreateInstance(IContext context) 
    { 
     //return the implementation based on type 
    } 
} 

這是在內核模塊綁定爲:

public class CoreModule : NinjectModule 
{ 
    public override void Load() 
    { 
     Bind<ICommonComponentVM>().ToProvider<ICommonComponentVMProvider>(); 
    } 
} 

如何從綁定中提取自定義參數IContext? 或者這是做到這一點的正確方法? Ninject wiki缺乏這個信息。

編輯

我到達

var param = context.Parameters.Single((arg) => arg.Name == "type"); 

param.GetValue訪問參數的值需要兩個參數:IContextITarget。我有context,但我應該怎麼把Target

在它的工作原理與null其間:

var type = (CommonVMTypes)param.GetValue(context, null); 

,所以它看起來是這樣的:

protected override ICommonComponentVM CreateInstance(IContext context) 
{ 
    var param = context.Parameters.Single((arg) => arg.Name == "type"); 
    if (param == null){ 
     return null; 
    } 
    var type = (CommonVMTypes)param.GetValue(context, null); //<-- Needs an Action ITarget 

    switch (type) 
    // ... 
} 

回答

1

您可以通過屬性ICollection<IParameter> IContext.Parameters訪問參數。您可以使用context.Parameters.Single(x => x.Name == "type")找到它。

您也可以繼承Parameter的子類或實現IParameter以獲得具有強類型信息的自定義參數類型,例如p.Ex. ComponentVMTypeParameter,然後使用context.Parameters.OfType<ComponentVMTypeParameter>().Single()進行選擇。

替代方法:

  • 使用條件綁定(When(...)語法,可以檢查參數,太),而不是供應商。不需要擴展提供者。
  • 使用factory而不是提供者。
  • 使用命名綁定:
    • Bind<IFoo>().To<Foo1>().Named("Foo1")
    • IResolutionRoot.Get<IFoo>("Foo1");

然而,在原則上沒有必要使用一個IProvider。你可以代替

但是,如果有我會考慮使用抽象工廠,而不是

+0

謝謝你的類型有限,我來到你的解決方案的第一部分。請參閱我的編輯。我需要最後一部分。無論如何,我接受你的回答 – Sanandrea

+0

關於'Factory',我會反過來用'Kernel.Get ()'實例化'ViewModels',因爲它們之間有依賴關係。 – Sanandrea

+0

@Sanandrea'var type =(CommonVMTypes)param.GetValue(context,null);'沒問題。實施並不要求目標具有任何價值。你使用它的方式,即使'context'沒有被訪問。 'Parameter'類是非常通用的,並且允許大量的用例。 – BatteryBackupUnit

相關問題