嗨我在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