C# 在提供程序Ninject中检索自定义绑定参数
您好,我正在一个C# 在提供程序Ninject中检索自定义绑定参数,c#,xamarin,mvvm,dependency-injection,ninject,C#,Xamarin,Mvvm,Dependency Injection,Ninject,您好,我正在一个XamarinMVVM项目中使用Ninject。我试图做的是基于枚举类型绑定特定实现: var foo = new Ninject.Parameters.Parameter("type", VMType, true); Kernel.Get<ICommonComponentVM>(foo); 但是使用param.GetValue访问参数的值需要两个参数:IContext和ITarget。我有上下文,但我应该把什么作为目标 同时,它与null一起工作: var typ
Xamarin
MVVM
项目中使用Ninject
。我试图做的是基于枚举类型绑定特定实现:
var foo = new Ninject.Parameters.Parameter("type", VMType, true);
Kernel.Get<ICommonComponentVM>(foo);
但是使用param.GetValue
访问参数的值需要两个参数:IContext
和ITarget
。我有上下文
,但我应该把什么作为目标
同时,它与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)
// ...
}
受保护的覆盖ICommonComponentVM CreateInstance(IContext上下文)
{
var param=context.Parameters.Single((arg)=>arg.Name==“type”);
if(param==null){
返回null;
}
var type=(CommonVMTypes)param.GetValue(context,null);//您可以通过属性ICollection IContext.parameters
访问参数。您可以使用context.parameters.Single(x=>x.Name==“type”)找到它
您还可以为具有强类型信息的自定义参数类型(例如,ComponentVMTypeParameter
)子类化Parameter
,或实现ipparameter
,然后使用context.Parameters.OfType().Single()选择它
备选办法:
- 使用条件绑定(
When(…)
语法,也可以检查参数)而不是提供程序。不需要扩展提供程序
- 使用提供程序而不是提供程序
- 使用命名绑定:
Bind().To().Named(“Foo1”)
IResolutionRoot.Get(“Foo1”);
但是,原则上不需要使用IProvider
。您可以改为使用
<>但是,如果有一个有限的类型,我会考虑使用一个抽象的工厂而不是谢谢,我到了你的解决方案的第一部分。请看我的编辑。我需要最后一部分。无论如何,我接受你关于“代码>工厂< /代码>的回答,我无论如何都会用<代码>内核实例化<代码> ViewModels <代码>。
因为它们之间的依赖关系。@Sanandreavar type=(CommonVMTypes)param.GetValue(context,null)
是可以的。实现不需要目标有任何值。使用它的方式,即使是上下文
也不会被访问。参数
类非常通用,允许很多用例。
var param = context.Parameters.Single((arg) => arg.Name == "type");
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)
// ...
}