Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - StructureMap Beginner | Property Injection

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...