Using default parameter values with Ninject 3.0

前端 未结 2 1713
无人共我
无人共我 2021-01-04 10:02

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 b

相关标签:
2条回答
  • 2021-01-04 10:41

    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.

    0 讨论(0)
  • 2021-01-04 10:43

    You can avoid setting AllowNullInjection globally while still injecting a parameter only when a binding exists by configuring your binding like this:

    Kernel.Bind<IEmployeeValidator>()
          .To<EmployeeValidator>()
          .WithConstructorArgument(typeof(IValidator<PersonName>), c => c.Kernel.TryGet<IValidator<PersonName>>());
    

    [Optional] is not needed for that.

    0 讨论(0)
提交回复
热议问题