小编Sim*_*mon的帖子

构造函数注入以及何时使用服务定位器

我正在努力理解StructureMap的部分用法.特别是,在文档中有一个关于常见反模式的声明,仅使用StructureMap作为服务定位器而不是构造函数注入(直接来自Structuremap文档的代码示例):

 public ShippingScreenPresenter()
    {
        _service = ObjectFactory.GetInstance<IShippingService>();
        _repository = ObjectFactory.GetInstance<IRepository>();
    }
Run Code Online (Sandbox Code Playgroud)

代替:

public ShippingScreenPresenter(IShippingService service, IRepository repository)
    {
        _service = service;
        _repository = repository;
    }
Run Code Online (Sandbox Code Playgroud)

这对于一个非常短的对象图很好,但是当处理很多级别的对象时,这是否意味着你应该从顶部向下传递更深层对象所需的所有依赖项?当然,这会破坏封装并暴露有关更深层对象实现的过多信息.

假设我正在使用Active Record模式,因此我的记录需要访问数据存储库才能保存和加载自身.如果此记录加载到对象内,该对象是否调用ObjectFactory.CreateInstance()并将其传递给活动记录的构造函数?如果该对象在另一个对象内部怎么办?是否将IRepository作为自己的参数进一步向上?这将向父对象公开我们此时访问数据存储库的事实,外部对象可能不应该知道.

public class OuterClass
{
    public OuterClass(IRepository repository)
    {
        // Why should I know that ThingThatNeedsRecord needs a repository?
        // that smells like exposed implementation to me, especially since
        // ThingThatNeedsRecord doesn't use the repo itself, but passes it 
        // to the record.
        // Also where do I create repository? Have to instantiate …
Run Code Online (Sandbox Code Playgroud)

structuremap dependency-injection service-locator constructor-injection

1
推荐指数
1
解决办法
2320
查看次数