繁体   English   中英

如何使用kernel.Get使用ninject创建对象以获取具有特定属性的绑定?

[英]How can I create an object with ninject using kernel.Get for a binding with a specific attribute?

对于我正在编写的测试,我想使用ninject创建一个对象,该对象按属性分类。 例如,我可以通过此考试吗?

using Ninject;
using NUnit.Framework;
using System;

namespace TestProject
{
    public class RedAttribute : Attribute { }
    public class BlueAttribute : Attribute { }

    public class TestClass
    {
        public string Str;

        public TestClass([Blue] String str)
        {
            Str = str;
        }
    }
    [TestFixture]
    public class SimpleTest
    {

        [Test]
        public void TestFunction()
        {
            IKernel kernel = new StandardKernel();

            kernel.Bind<string>()
                .ToMethod(context => "Red String")
                .WhenTargetHas<RedAttribute>();

            kernel.Bind<string>()
                .ToMethod(context => "Blue String")
                .WhenTargetHas<BlueAttribute>();
            kernel.Bind<TestClass>().ToSelf();

            // this works fine
            TestClass testC = kernel.Get<TestClass>();
            Assert.That(testC.Str, Is.EqualTo("Blue String"));

            // but I can't get the below to work
            // Ideally I would like something statically typed, eg
            // string str = kernel.Get<string, BlueAttribute>();
            string str = "TODO ?????";
            Assert.That(str, Is.EqualTo("Blue String"));

        }
    }
}

代码kernel.Get<string, BlueAttribute>(); 会变得很复杂。 你可以做类似的事情

var request = new Request(
    null,
    typeof (string),
    new ParameterTarget(
        "get method/constructor by reflection",
        "get parameter info of parameter with [Blue attribute]"),
    x => (object)null);
string str = kernel.Resolve(request).OfType<string>().Single();

您可能还创建了一个动态类型,而不是编写一个动态类型并使用反射来获取构造函数/参数信息。 或者,您可以使用IL发光创建一个。

但是我认为创建一个伪类很简单。 实际上,您不需要kernel.Bind<TestClass>().ToSelf(); ,因为它是一个可实例化的类,所以ninject无需绑定即可解决它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM