在Provider Ninject中检索自定义绑定参数

时间:2017-05-31 11:38:55

标签: c# xamarin mvvm dependency-injection ninject

您好我在$titles = DB::table('books') ->where('books.year', 1994) ->leftjoin('journals as journals', 'books.year', '=', 'journals.year') ->leftjoin('newspapers as newspapers', 'books.year', '=', 'newspapers.year') ->select('books.title', 'journals.title', 'newspapers.title') ->get(); Ninject项目中使用Xamarin。我想要做的是基于枚举类型绑定特定的实现:

MVVM

和提供者:

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>(); } } 中提取自定义参数? 或者这是正确的方法吗? Ninject wiki缺少此信息。

修改

我到了

IContext

但是使用var param = context.Parameters.Single((arg) => arg.Name == "type"); 访问参数的值需要两个参数:param.GetValueIContext。我有ITarget,但我应该将其作为context

与此同时,它适用于Target

null

所以它看起来像这样:

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

1 个答案:

答案 0 :(得分:1)

您可以通过属性ICollection<IParameter> IContext.Parameters访问参数。您可以使用context.Parameters.Single(x => x.Name == "type")找到它。

您还可以将ParameterIParameter子类化为具有强类型信息的自定义参数类型,p.Ex。 ComponentVMTypeParameter然后使用context.Parameters.OfType<ComponentVMTypeParameter>().Single()选择它。

替代方法:

  • 使用条件绑定(When(...)语法,也可以检查参数)而不是提供者。不需要扩展提供者。
  • 使用factory代替提供商。
  • 使用命名绑定:
    • Bind<IFoo>().To<Foo1>().Named("Foo1")
    • IResolutionRoot.Get<IFoo>("Foo1");

但是,原则上不需要使用IProvider。你可以改为

但是,如果我考虑使用抽象工厂的类型数量有限