[英]Ninject : How Get inherited type instead Base type when inherited type marked by attribute
通過屬性標記繼承的類型時,如何獲取繼承的類型而不是基本類型?
我們可以用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();
}
查看約定擴展。 應該直截了當。 就像是
kernel.Bind(x =>
{
x.FromThisAssembly()
.SelectAllClasses()
.WithAttribute<SomeAttribute>()
.BindBase();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.