簡體   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