首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ninject.Extensions.Conventions在基于接口和BaseClass的列表绑定中注入单节点

Ninject.Extensions.Conventions在基于接口和BaseClass的列表绑定中注入单节点
EN

Stack Overflow用户
提问于 2013-02-19 21:08:19
回答 1查看 758关注 0票数 2

我得到了以下将失败的测试案例:

预期:与ArxScriptsTests.Engines.Ioc.Examples+A相同,但为: ArxScriptsTests.Engines.Ioc.Examples+A

问题是,怎样才能把它做好?

代码语言:javascript
复制
[TestFixture]
public class Examples
{
    public interface IInterface
    {

    }

    public abstract class BaseClass : IInterface
    {

    }

    public class A : BaseClass
    {

    }

    public class B : BaseClass
    {

    }


    [Test]
    public void TestMethod1()
    {
        IKernel kernel = new StandardKernel();

        // Bind to self
        kernel.Bind(x => x
            .FromThisAssembly()
            .SelectAllClasses().InheritedFrom<BaseClass>()
            .BindToSelf()
            .Configure(b => b.InSingletonScope())
            );

        // Bind to IInterface
        kernel.Bind(x => x
            .FromThisAssembly()
            .SelectAllClasses().InheritedFrom<IInterface>()
            .BindSelection((type, baseTypes) => new List<Type> { typeof(IInterface) })
            .Configure(b => b.InSingletonScope())
            );


        // Bind to BaseClass
        kernel.Bind(x => x
            .FromThisAssembly()
            .SelectAllClasses().InheritedFrom<BaseClass>()
            .BindSelection((type, baseTypes) => new List<Type> { typeof(BaseClass) })
            .Configure(b => b.InSingletonScope())
            );




        List<IInterface> byInterface = new List<IInterface>(kernel.GetAll<IInterface>());
        List<BaseClass> byBaseClass = new List<BaseClass>(kernel.GetAll<BaseClass>());


        Assert.AreSame(byInterface[0], byBaseClass[0]);
    }
}

的一个解决方案是

代码语言:javascript
复制
[Test]
public void TestMethod1()
{
    IKernel kernel = new StandardKernel();

    // Bind to Both
    kernel.Bind(x => x
        .FromThisAssembly()
        .SelectAllClasses().InheritedFrom<IInterface>()
        .BindSelection((type, baseTypes) => new List<Type> { typeof(IInterface), typeof(BaseClass) })
        .Configure(b => b.InSingletonScope())
        );


    List<IInterface> byInterface = new List<IInterface>(kernel.GetAll<IInterface>());
    List<BaseClass> byBaseClass = new List<BaseClass>(kernel.GetAll<BaseClass>());


    Assert.AreSame(byInterface[0], byBaseClass[0]);
}

但是,当我尝试将这两个绑定放在不同的模块中时,这将于事无补。或者说这是个坏主意?

EN

回答 1

Stack Overflow用户

发布于 2013-02-20 12:01:08

范围是为绑定定义的。两个绑定不可能共享范围。

你应该做的是:

  1. 使用接口而不是BaseClass
  2. Fins是一种编码约定,用来定义哪种类型的calsses是单子。例如,特殊的命名,比如在服务中结束
  3. 使用BindAllInterfaces进行Bindind

在使用约定时,不应该从使用者的角度,而应该从服务提供者的角度来进行。因此,不需要对不同模块中的不同接口类型进行绑定。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14967453

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档