简体   繁体   English

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

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

For a test I'm writing I would like to create an object with ninject that is classified with an attribute. 对于我正在编写的测试,我想使用ninject创建一个对象,该对象按属性分类。 Eg, can I make this test pass? 例如,我可以通过此考试吗?

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"));

        }
    }
}

The code kernel.Get<string, BlueAttribute>(); 代码kernel.Get<string, BlueAttribute>(); will get quite complicated. 会变得很复杂。 You can do something like 你可以做类似的事情

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();

You might also create a dynamic type instead of writing one and using reflection to get the constructor / parameter info. 您可能还创建了一个动态类型,而不是编写一个动态类型并使用反射来获取构造函数/参数信息。 Or you could use IL emitting to create one. 或者,您可以使用IL发光创建一个。

But i think creating a fake class is way simpler. 但是我认为创建一个伪类很简单。 Actually you don't need the kernel.Bind<TestClass>().ToSelf(); 实际上,您不需要kernel.Bind<TestClass>().ToSelf(); , since it's an instantiatable class, ninject can resolve it without there being a binding. ,因为它是一个可实例化的类,所以ninject无需绑定即可解决它。

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

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