StructureMap初学者|地产注入 [英] StructureMap Beginner | Property Injection
问题描述
这个问题的一部分是已经在这里问: structuremap物业注射但答案从来没有给出。
Part of this question was already asked here : structuremap Property Injection but the answer was never given.
使用StructureMap,是有可能做地产注入,使得
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
推荐答案
StructureMap支持<一个href=\"http://structuremap.net/structuremap/ConstructorAndSetterInjection.htm#section4\">setter/property注射。所以,你可以做到以下几点:
StructureMap supports setter/property injection. So you could do the following:
public class SomeController : Controller
{
[SetterProperty]
public IService Service { get; set; }
}
和则:
ObjectFactory.Initialize(x =>
{
x.For<IService>()
.Use<ServiceImpl>();
});
如果你不喜欢塞满您的控制器,StructureMap特定属性,你可以这样配置的思路:
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();
});
另外请注意,财产注射适用于场景中这个属性的presence不是强制性的控制器的正常运行。例如觉得记录仪。如果控制器的消费者不注入任何具体的实施记录仪进入地产控制器仍然有效,它只是它不记录。在你的情况,你正在使用的服务,我会用构造函数注入,如果你的控制器动作依赖此服务。所以,你应该问自己的问题是:我的控制器死机当我打电话一些行动,如果这个属性是空
?如果这个问题的答案是肯定的话,我会建议构造函数注入。此外,当你使用一个构造器注入强制该控制器的消费者指定实现,因为他不能没有在构造函数中传递一个合适的服务获得控制器的一个实例。
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.
这篇关于StructureMap初学者|地产注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!