嗨我在Xamarin
MVVM
項目中使用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
訪問參數的值需要兩個參數:IContext
和ITarget
。我有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)
// ...
}
謝謝你的類型有限,我來到你的解決方案的第一部分。請參閱我的編輯。我需要最後一部分。無論如何,我接受你的回答 – Sanandrea
關於'Factory',我會反過來用'Kernel.Get()'實例化'ViewModels',因爲它們之間有依賴關係。 –
Sanandrea
@Sanandrea'var type =(CommonVMTypes)param.GetValue(context,null);'沒問題。實施並不要求目標具有任何價值。你使用它的方式,即使'context'沒有被訪問。 'Parameter'類是非常通用的,並且允許大量的用例。 – BatteryBackupUnit