I am trying to setup setter/property injection for my MVC project using StructureMap, but I can't seem to get it to set the properties. I am well aware that Constructor injection is the recommended practice, but I have a strict requirement that requires we do it using setter injection, so please hold the comments attempting to tell me otherwise.
I have the normal boilerplate setup code such as the following in my 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>();
});
});
My TestControllerFactory looks like the following:
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 ;
}
}
I have the following Service/Implementation class pair
public interface IPaymentService
{
}
public class PaymentService:IPaymentService
{
}
And finally, I have my controller that will have the property that needs to have the concrete payment service implementation injected into it:
public class HomeController:Controller { public IPaymentService Service {get;set;}
public ActionResult Index(){
var test = Service... //Service is Null
}
}
Shown above, the property remains null when I debug.
Additionally, I have tried using the [SetterProperty] just to see if it worked(I have no intention of coupling my controllers with those attributes), and it still didnt work.
I am not sure if I need to do something else, or what the problem might be. I have been using constructor injection with StructureMap for quite awhile.
Try dropping this line:
x.ForConcreteType<HomeController>().Configure
.Setter<IPaymentService>(y => y.PaymentService).IsTheDefault();
It shouldn't be necessary.
Given the following controller:
public class HomeController : Controller
{
public IMsgService Service { get; set; }
public ActionResult Index()
{
return Content(Service.GetMessage());
}
}
This was all that was required to configure StructureMap to set the property:
ObjectFactory.Initialize(cfg =>
{
cfg.For<IMsgService>().Use<MyMsgService>();
cfg.SetAllProperties(prop =>
{
prop.OfType<IMsgService>();
});
});
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With