我想使用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構造函數注入。
你有Setter注入任何運氣?我試圖在動作過濾器,但它似乎也沒有工作。 – ntombela
經過努力注入二傳手後,我決定離開它。 – Joel