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 which marked by
// SomeAttribute 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();
});