StructureMap Beginner | Property Injection
Asked Answered
O

2

8

Part of this question was already asked here : structuremap Property Injection but the answer was never given.

With StructureMap, is it possible to do Property Injection such that

class SomeController : Controller
{
 public IService Service
 {
  get;
  set;
 }
}

gets injected properly? I am a

Owen answered 12/2, 2011 at 17:26 Comment(0)
V
19

StructureMap supports setter/property injection. So you could do the following:

public class SomeController : Controller
{
    [SetterProperty]
    public IService Service { get; set; }
}

and then:

ObjectFactory.Initialize(x =>
{
    x.For<IService>()
     .Use<ServiceImpl>();
});

or if you don't like the idea of cluttering your controllers with StructureMap specific attributes you could configure it like this:

ObjectFactory.Initialize(x =>
{
    x.For<IService>()
     .Use<ServiceImpl>();

    x.ForConcreteType<SomeController>()
     .Configure
     .Setter<IService>(c => c.Service)
     .IsTheDefault();
});

Also note that property injection is suitable in scenarios where the presence of this property is not compulsory for the correct functioning of the controller. For example think of a logger. If the consumer of the controller doesn't inject any specific implementation of a logger into the property the controller still works it's just that it doesn't log. In your case you are using a service and I would use constructor injection if your controller actions depend on this service. So the question you should ask yourself is: will my controller crash when I call some its action if this property is null? If the answer to this question is yes then I would recommend constructor injection. Also when you use a constructor injection you force the consumer of this controller to specify an implementation because he cannot obtain an instance of the controller without passing a proper service in the constructor.

View answered 12/2, 2011 at 20:26 Comment(2)
Thanks Darin. I am still trying to decide between StructureMap and Castle.Windsor for my project, and property injection is very important to me. Do you know if StructureMap can inject into MVC Action Filters or Model Binders?Owen
Also, the property to which the setter attribute is being applied must be public. (At least that's what I've found) That makes perfect sense but is easy to overlook if you're adding it to an existing class & prop, as I was. Otherwise your property will be null.Alternately
T
4

To inject dependencies for all properties of a certain type, use the SetAllProperties method as part of the initialization of your ObjectFactory:

ObjectFactory.Initialize(x =>
{
   x.SetAllProperties(x => x.OfType<IService>());
});

It is also possible to define policies for setter injection, see this post.

Tain answered 3/3, 2012 at 20:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.