开发者

Ninject Contextual Binding Based on Method's Parameter Value

I am attempting to use ninjects contextual binding functionality to bind to the correct implementation of an interface based on the value of an enum parameter passed into a method, and I'm stuck. I thought I could accomplish this using metadata. Here's what I tried and its not working.

    enum Colors
    {
        Red,
        Blue
    }

    public interface IColor
    {}

    pu开发者_JAVA技巧blic class Red : IColor
    {}

    public class Blue : IColor
    {}

    class Test
    {
        private readonly StandardKernel _kernal;
        public Test()
        {
            _kernal = new StandardKernel();
            _kernal.Bind<IColor>().To<Red>().WithMetadata("color", Colors.Red);
            _kernal.Bind<IColor>().To<Blue>().WithMetadata("color", Colors.Blue);
        }

        public void TestMethod(Colors color)
        {
            IColor iColor = _kernal.Get<IColor>(m => m.Get<Colors>("color") == color);
        }
    }

Any thoughts? Thanks


Yes this works. If you create a new class library with latest ninject and NUnit, you can run to following to verify:

enum Colors
{
    Red,
    Blue
}

public interface IColor
{ }

public class Red : IColor
{ }

public class Blue : IColor
{ }

class Test
{
    private readonly StandardKernel _kernal;
    public Test()
    {
        _kernal = new StandardKernel();
        _kernal.Bind<IColor>().To<Red>().WithMetadata("color", Colors.Red);
        _kernal.Bind<IColor>().To<Blue>().WithMetadata("color", Colors.Blue);
    }

    public IColor TestMethod(Colors color)
    {
        return _kernal.Get<IColor>(m => m.Get<Colors>("color") == color);
    }
}

[TestFixture]
public class TestMetadataFunctions
{
    [Test]
    public void test_method_should_return_specified_color()
    {
        var test = new Test();
        var color = test.TestMethod(Colors.Red);

        Assert.IsInstanceOf(typeof(Red), color);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜