我有一个接口和一个实现该接口的类。该类具有默认静态实例,也可以显式构造(传递参数)。
如何配置 StrucutreMap 以使默认实例是静态实例,如果我请求一个带有参数的实例,则构造一个新实例?
这是失败的测试
[TestFixture]
public class StructureMapTests
{
[Test]
public void Test_same_interface_default_implemenation_and_with_parameter()
{
IMyInterface defaultImp = new MyImpl(0);
ObjectFactory.Initialize(x =>
{
x.For<IMyInterface>().Use(defaultImp);
x.For<IMyInterface>().Add<MyImpl>().Ctor<int>().IsTheDefault();
});
Assert.AreEqual(defaultImp, ObjectFactory.GetInstance<IMyInterface>());
var instance1 = ObjectFactory.With("value").EqualTo(1).GetInstance<IMyInterface>();
Assert.AreEqual(true, instance1 != defaultImp); //<-- fails here
Assert.AreEqual(1, instance1.GetValue());
var instance2 = ObjectFactory.With("value").EqualTo(2).GetInstance<IMyInterface>();
Assert.AreEqual(true, instance1 != defaultImp);
Assert.AreEqual(2, instance2.GetValue());
}
public interface IMyInterface
{
int GetValue();
}
public class MyImpl : IMyInterface
{
private int _value;
public MyImpl(int value)
{
_value = value;
}
public int GetValue()
{
return _value;
}
}
}