views:

702

answers:

1

I'm new to IOC containers and learning Ninject. I've using version 2.0, freshly downloaded from Github.

I'm trying to set a string parameter on a constructor when a default constructor is also present. I've been stepping through the Ninject source but I'm insufficiently familiar with the patterns being used to easily pinpoint what I am missing.

Here is my test console app:

        static void Main(string[] args)
        {
        IKernel kernel = new StandardKernel();
        kernel.Bind<ITestClass>().To<TestClass>()
            .WithConstructorArgument("message", "Hello World!");

        var testClass = kernel.Get<ITestClass>();

        // Does not work either:
        //var testClass = kernel.Get<ITestClass>(new ConstructorArgument("message", "Hello World!"));

        testClass.DisplayMessage();
        Console.ReadLine();
        }
    }

public interface ITestClass
    {
    void DisplayMessage();
    }

public class TestClass : ITestClass
    {
    public TestClass()
        {
        this.message = "Wrong message :(";
        }

    private string message;
    public TestClass(string message)
        {
        this.message = message;
        }

    public void DisplayMessage()
        {
        Console.WriteLine(this.message);
        }

The code prints "Wrong message :(" to the console. If I remove the default constructor in TestClass I get "Hello World!". What am I missing here?

To clarify: I want the class to print "Hello World!" to the console with the default constructor present.

+6  A: 

string is not self-bindable, so it isn't counted as a dependency. When the .ctor scorer runs, it will score the default .ctor and the string .ctor the same since the dependency can't be resolved. You can fix this by attributing your string .ctor

[Inject] 
public TestClass(string message){...}

and your code will work fine.

Ian Davis
Thanks a lot Ian!
Stuart
I just committed a patch earlier today that should have also taken care of this issue without the [Inject] attribute. Parameters are now scored when evaluating which .ctor to use.
Ian Davis