使用默认参数值与Ninject 3.0 [英] Using default parameter values with Ninject 3.0

查看:150
本文介绍了使用默认参数值与Ninject 3.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有与具有默认值的参数的构造函数的类。随着Ninject 2.2,它将履行 [可选] 属性,做工精细的没有绑定定义的反对声明,像这样的构造:



 公共EmployeeValidator(; PersonName的> personNameValidator = NULL [可选] IValidator<) p> 

由于升级到Ninject 3.0,此对象的构造失败,提示信息,说明该供应商返回null:




试验方法ValidatorIsolated.Tests.EmployeeValidatorTest.CreateEmployeeValidatorTest抛出异常:



Ninject.Activati​​onException:使用条件隐自我约束的错误激活IValidator {} PersonName的。IValidator {PersonName的}



提供商返回null



激活路径:



2)的依赖IValidator {PersonName的}注射入式EmployeeValidator的构造函数的参数personNameValidator



1)请给IValidator {员工}



建议:



1)确保供应商正确处理创建请求




[可选] 当一个参数的默认值是存在,什么是处理的最佳方式属性仍然遵守注射可选参数,如本?


解决方案

可选属性在这种情况下被忽略,因为总是有缺省值服务现有但所提供的值为null。 null是不是默认允许值。



您可以覆盖NinjectSettings.AllowNullInjection设置为true这一行为。


I have a class with a constructor having a parameter with a default value. With Ninject 2.2, it would honor the [Optional] attribute and work fine with no binding defined against a constructor declared like so:

public EmployeeValidator([Optional] IValidator<PersonName> personNameValidator = null)

Since upgrading to Ninject 3.0, construction of this object fails with a message stating that the provider returned null:

Test method ValidatorIsolated.Tests.EmployeeValidatorTest.CreateEmployeeValidatorTest threw exception:

Ninject.ActivationException: Error activating IValidator{PersonName} using conditional implicit self-binding of IValidator{PersonName}

Provider returned null.

Activation path:

2) Injection of dependency IValidator{PersonName} into parameter personNameValidator of constructor of type EmployeeValidator

1) Request for IValidator{Employee}

Suggestions:

1) Ensure that the provider handles creation requests properly.

Is the [Optional] attribute still honored when a default value for a parameter is present and what is the best way to handle injection with optional parameters such as this?

解决方案

The Optional Attribute is ignored in this situation because there is always the default value available- But the provided value is null. Null is not an allowed value by default.

You can override this behavior by setting NinjectSettings.AllowNullInjection to true.

这篇关于使用默认参数值与Ninject 3.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆