Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using default parameter values with Ninject 3.0

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?

like image 584
The Davester Avatar asked May 09 '12 14:05

The Davester


2 Answers

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.

like image 158
Dark Daskin Avatar answered Oct 19 '22 12:10

Dark Daskin


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.

like image 37
Remo Gloor Avatar answered Oct 19 '22 11:10

Remo Gloor