Ninject:当属性标记的继承类型时,如何获取继承类型而不是Base类型

问题描述 投票:0回答:1

当继承的类型由属性标记时,如何获取继承类型而不是基类型?

我们可以用Ninject做到吗?这就是我所拥有的:

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

    // use Method which return properly type
    kernel.Bind<IBase>().ToMethod(context => SOMEMETHOD());

    // should be return DerivedClass 
    BaseClass derived = kernel.Get<BaseClass>();
    BaseClass1 derived1 = kernel.Get<BaseClass1>();

    // The result should be:
    derived.WhoIAm();  //--> "DerivedClass"
    derived1.WhoIAm(); //--> "DerivedClass1"
}

// method which resolve this
static object SOMEMETHOD()
{
    // return derived class wich marked by
    // SomeAttribure where base class that which we use in kernel.Get 
}    

基础类

class BaseClass : IBase
{    
    public virtual void WhoIAm()
    {
        Console.Write(this.GetType());
    }   
}

class BaseClass1 : IBase
{    
    public virtual void WhoIAm()
    {
        Console.Write(this.GetType());
    }   
}

继承的类。 SomeAttribute是一个标记应该创建的类型的属性

[SomeAttribute]
class DerivedClass : BaseClass
{
    public override void WhoIAm()
    {
        Console.Write(this.GetType());
    }
}    

其他派生类继承自BaseClass1

[SomeAttribute]
class DerivedClass1 : BaseClass1
{
    public override void WhoIAm()
    {
        Console.Write(this.GetType());
    }
}    
class SomeAttribute : Attribute {}

interface IBase
{
    void WhoIAm();
}
c# dependency-injection ninject inversion-of-control ioc-container
1个回答
0
投票

查看约定扩展。应该是直截了当的。就像是

kernel.Bind(x =>
{
    x.FromThisAssembly()
     .SelectAllClasses()
     .WithAttribute<SomeAttribute>()
     .BindBase();
});
© www.soinside.com 2019 - 2024. All rights reserved.