我得到了以下将失败的测试案例:
预期:与ArxScriptsTests.Engines.Ioc.Examples+A相同,但为: ArxScriptsTests.Engines.Ioc.Examples+A
问题是,怎样才能把它做好?
[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]);
}
}的一个解决方案是
[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]);
}但是,当我尝试将这两个绑定放在不同的模块中时,这将于事无补。或者说这是个坏主意?
发布于 2013-02-20 12:01:08
范围是为绑定定义的。两个绑定不可能共享范围。
你应该做的是:
BaseClass在使用约定时,不应该从使用者的角度,而应该从服务提供者的角度来进行。因此,不需要对不同模块中的不同接口类型进行绑定。
https://stackoverflow.com/questions/14967453
复制相似问题