6

我想使用StructureMap爲我的MVC項目設置setter/property注入,但我似乎無法得到它來設置屬性。我很清楚Constructor注入是推薦的做法,但我有一個嚴格的要求,要求我們使用setter注入來進行注入,所以請保留試圖告訴我的註釋。StructureMap設置注入沒有設置屬性

我有正常的樣板設置代碼,如我的Global.asax以下

ControllerBuilder.Current.SetControllerFactory(new TestControllerFactory()); 

ObjectFactory.Initialize(x => { 
      x.For<IPaymentService>().Use<PaymentService>(); 
      x.ForConcreteType<HomeController>().Configure.Setter<IPaymentService>(y => y.PaymentService).IsTheDefault(); 
      x.SetAllProperties(y => 
      { 
       y.OfType<IPaymentService>(); 
      }); 

     }); 

我TestControllerFactory如下所示:

public class TestControllerFactory:System.Web.Mvc.DefaultControllerFactory 
{ 
    protected IController GetControllerInstance(Type controllerType) 
    { 
     if (controllerType == null) 
      throw new ArgumentNullException("controllerType"); 
     return ObjectFactory.GetInstance(controllerType) as IController ; 
    } 
} 

我有以下服務/實現類對

public interface IPaymentService 
{ 

} 

public class PaymentService:IPaymentService 
{ 

} 

最後,我有我的控制器, l具備,需要有注入到它的具體支付服務實現屬性:

公共類HomeController的:控制 { 公共IPaymentService服務{獲取;集;}

public ActionResult Index(){ 
     var test = Service... //Service is Null 
} 

}

如上所示,當我調試時,該屬性保持爲空。

此外,我已經嘗試使用[SetterProperty]只是爲了看它是否工作(我沒有打算與這些屬性耦合我的控制器),它仍然沒有工作。

我不確定是否需要做別的事情,或者可能出現什麼問題。我一直在使用StructureMap構造函數注入。

+0

你有Setter注入任何運氣?我試圖在動作過濾器,但它似乎也沒有工作。 – ntombela

+0

經過努力注入二傳手後,我決定離開它。 – Joel

回答

3

嘗試下探這一行:

x.ForConcreteType<HomeController>().Configure 
    .Setter<IPaymentService>(y => y.PaymentService).IsTheDefault(); 

它不應該是必要的。

鑑於以下控制器:

public class HomeController : Controller 
{ 
    public IMsgService Service { get; set; } 

    public ActionResult Index() 
    { 
     return Content(Service.GetMessage()); 
    } 
} 

這是被要求配置StructureMap設置該屬性都:

ObjectFactory.Initialize(cfg => 
{ 
    cfg.For<IMsgService>().Use<MyMsgService>(); 

    cfg.SetAllProperties(prop => 
    { 
     prop.OfType<IMsgService>(); 
    }); 
}); 

ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory()); 
+0

如果該屬性位於'controller'類中,則此解決方案正常工作,在我的情況下,該屬性是「非控制器」類,因此您的答案對我無能爲力。 –

+0

它不應該做任何差異*提供*您已經配置StructureMap與對象圖中的所有依賴關係。 –

+0

我把我的屬性'IUnitOfWork'放在我的控制器中,它獲取值,但是當我把它放在另一個類MyServiceFactory中並在我的控制器中實例化MyServiceFactory類時,IUnitOfWork屬性爲null。 –