简体   繁体   中英

Ninject : How Get inherited type instead Base type when inherited type marked by attribute

How do I get the inherited type instead of the base type when the inherited type is marked by attribute?

Can we do it with Ninject or not? Here's what I have:

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 
}    

Base Classes

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

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

Inherited Classes. SomeAttribute is an attribute that marks the type that should be created

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

Other Derived classes inheriting from BaseClass1

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

interface IBase
{
    void WhoIAm();
}

Look at the convention extension. Should be straight forward. Something like

kernel.Bind(x =>
{
    x.FromThisAssembly()
     .SelectAllClasses()
     .WithAttribute<SomeAttribute>()
     .BindBase();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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