[英]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? 我们可以用Ninject做到吗? 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
是一个属性,用于标记应创建的类型
[SomeAttribute]
class DerivedClass : BaseClass
{
public override void WhoIAm()
{
Console.Write(this.GetType());
}
}
Other Derived classes inheriting from BaseClass1
从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();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.