Water Cooler v2
Water Cooler v2

Reputation: 33850

How do I inject a property of a primitive type using Ninject?

How do I inject the name "Tommy" into the Name property of Bar when instantiating / activating a Foo object?

class Foo
    {
        public Bar Bar { get; set; }

        public Foo(Bar b) { Bar = b; }
    }

    class Bar
    {
        [Inject]
        public string Name { get; set; }
    }

Upvotes: 0

Views: 133

Answers (2)

BatteryBackupUnit
BatteryBackupUnit

Reputation: 13233

Alternatively, this is more refactor-safe:

kernel.Bind<Bar>().ToSelf().OnActivation(bar => bar.Name = "Tommy");

but beware, you should only use property injection when there's no alternatives. Objects should be built up by the constructor - i.E. after the constructor was run they should have all they need to operate. So maybe you should inject the value into the constructor instead.

Upvotes: 2

ovolko
ovolko

Reputation: 2797

kernel.Bind<Bar>().ToSelf().WithPropertyValue("Name", "Tommy");

Upvotes: 1

Related Questions