2017-05-31 118 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

相关问题