2012-04-18 54 views
0

我有一個接口和一個實現該接口的類。該類有一個默認的靜態實例,也可以顯式構造(傳遞參數)。StructureMap默認實例和附加顯式參數

如何配置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; 
     } 
    } 
} 

回答

0

我認爲,你所面臨的問題是,對於同一個接口註冊多個實現時,最後一個是要通過的GetInstance解決的一個測試。要解決這個問題,你可以命名你的配置。

嘗試以下操作:

[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>().Add<MyInterface>().Named("withArgument").Ctor<int>().IsTheDefault();           
             x.For<IMyInterface>().Use(defaultImp).Named("default"); 
            }); 

     Assert.AreEqual(defaultImp, ObjectFactory.GetInstance<IMyInterface>()); 

     var instance1 = ObjectFactory.With("value").EqualTo(1).GetInstance<IMyInterface>("withArgument"); 
     Assert.AreEqual(true, instance1 is MyInterface); 
     Assert.AreEqual(1, instance1.GetValue()); 

     var instance2 = ObjectFactory.With("value").EqualTo(2).GetInstance<IMyInterface>("withArgument"); 
     Assert.AreEqual(true, instance2 is MyInterface); 
     Assert.AreEqual(2, instance2.GetValue()); 
    } 

    public interface IMyInterface 
    { 
     int GetValue(); 
    } 

    private class MyInterface : IMyInterface 
    { 
     private int _value; 

     public MyInterface(int value) 
     { 
      _value = value; 
     } 

     public int GetValue() 
     { 
      return _value; 
     } 
    } 
}