结构图初学者 |属性注入 [英] StructureMap Beginner | Property Injection

查看:21
本文介绍了结构图初学者 |属性注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里已经有人问过这个问题的一部分:structuremap Property Injection 但从未给出答案.

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;
 }
}

被正确注入?我是一个

推荐答案

StructureMap 支持 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();
});

另请注意,属性注入适用于该属性的存在不是控制器正确运行所必需的场景.例如,想想一个记录器.如果控制器的使用者没有将记录器的任何特定实现注入到属性中,控制器仍然可以工作,只是它没有记录.在您的情况下,您使用的是服务,如果您的控制器操作依赖于该服务,我将使用构造函数注入.所以你应该问自己的问题是:如果这个属性是 null,当我调用它的一些动作时,我的控制器会崩溃吗?如果这个问题的答案是肯定的,那么我会推荐构造函数注入.此外,当您使用构造函数注入时,您会强制此控制器的使用者指定一个实现,因为他无法在未在构造函数中传递适当服务的情况下获取控制器的实例.

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.

这篇关于结构图初学者 |属性注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆