StructureMap Setter Injection does not set a property

I am trying to set setter / property setting for my MVC project using StructureMap, but I cannot get it to set properties. I well know that constructor injection is the recommended practice, but I have a strict requirement that requires us to do this using the installer injection, so please keep comments trying to tell me about it.

I have a normal template customization code like 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 is as follows:

 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 pair of service / implementation classes

 public interface IPaymentService { } public class PaymentService:IPaymentService { } 

And finally, I have my controller, which will have a property, which should have a specific implementation of the payment service, embedded in it:

public class HomeController: controller {public service IPaymentService {get; set;}

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

}

As shown above, the property remains zero when debugging.

Also, I tried to use [SetterProperty] just to make sure it worked (I'm not going to associate my controllers with these attributes), and it still didn't work.

I'm not sure if I need to do anything else or what might be the problem. I have been using design injection with StructureMap for quite some time.

+6
source share
1 answer

Try discarding this line:

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

It's not obligatory.

Given the following controller:

 public class HomeController : Controller { public IMsgService Service { get; set; } public ActionResult Index() { return Content(Service.GetMessage()); } } 

That was all that was needed 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()); 
+3
source

Source: https://habr.com/ru/post/925885/


All Articles