【问题标题】:Ninject : How Get inherited type instead Base type when inherited type marked by attributeNinject:如何获取继承类型而不是基类型,当继承类型由属性标记时
【发布时间】:2016-09-28 13:47:52
【问题描述】:

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

我们可以用 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】:

    查看约定扩展。应该直截了当。类似的东西

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-27
      • 2015-11-18
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 2018-09-27
      相关资源
      最近更新 更多