views:

143

answers:

1

I'm trying to work with NInject but fail on this simple case: I have 2 implementations for for IMessage like this

public interface IMessage
{
    string Message();
}

public class WelcomeMessage: IMessage
{
    #region IMessage Members

    public string Message()
    {
        return "Welcome user!";
    }

    #endregion
}
 public class AbortMessage: IMessage
{
    #region IMessage Members

    public string Message()
    {
        return "Abort user!";
    }

    #endregion
}

 public class MessageWrapper
{
    IMessage _mesgr;
    [Inject]
    public MessageWrapper(IMessage mesgr)
    {
        _mesgr = mesgr;
    }
    public override string ToString()
    {
        return _mesgr.Message();
    }
}

I register them like this:

public class MessageModule: StandardModule
{
    public override void Load()
    {
        Bind<IMessage>().To<WelcomeMessage>().Only(When.Context.Variable("Mesg").EqualTo("Welcome"));
        Bind<IMessage>().To<AbortMessage>().Only(When.Context.Variable("Mesg").EqualTo("Abort"));
        Bind<MessageWrapper>().ToSelf();
    }
}

Now in my test if I get the interface only it works fine, but complains for the class

static void Main(string[] args)
    {
        IKernel kernel = new StandardKernel(new MessageModule());

        Console.Write("Enter 1 for Welcome and 2 for Abort message: ");
        ConsoleKeyInfo info = Console.ReadKey(false);
        string Mesg = (info.Key == ConsoleKey.D1 ? "Welcome" : "Abort");

        //This works kernet.Get<IMessage>(With.Parameters.ContextVariable("Mesg", Mesg));
        Console.WriteLine();
        MessageWrapper objMesg = kernel.Get<MessageWrapper>(With.Parameters.ContextVariable("Mesg", Mesg));
        Console.WriteLine(objMesg);

        Console.ReadKey();
    }

How do I get it to inject the correct interface into the MessageWrapper and return it ? I don't want to do a Get in the constructor call for MessageWrapper.

thanks Sunit