构造函数注射和默认的重载 [英] Constructor injection and default overloads

查看:100
本文介绍了构造函数注射和默认的重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我们有

public interface ITimestampProvider
{
    DateTime GetTimestamp();
}

和一类消耗它

public class Timestamped
{
    private ITimestampProvider _timestampProvider

    public Timestamped(ITimestampProvider timestampProvider)
    {
        // arg null check

        _timestampProvider = timestampProvider;
    }

    public DateTime Timestamp { get; private set; }

    public void Stamp()
    {
        this.Timestamp = _timestampProvider.GetTimestamp();
    }
}

和的默认实现:

public sealed class SystemTimestampProvider : ITimestampProvider
{
    public DateTime GetTimestamp()
    {
        return DateTime.Now;
    }
}

它是有益还是harfmful介绍此构造?

Is it helpful or harfmful to introduce this constructor?

public Timestamped() : this(new SystemTimestampProvider())
{}

这是一个普遍的问题,即时间戳是不是有趣的部分。

This is a general question, i.e. timestamping is not the interesting part.

推荐答案

我认为这取决于具体的方案,并且基本上是一个功能谁在消费code是(库与应用程序),以及是否重新使用IoC容器或没有。

I think it depends on the scenario, and is basically a function of who the consumer the code is (library vs. application) and whether you're using an IoC container or not.

  • 如果您使用的是IoC容器,这是不是公共API的一部分,然后让容器做繁重,而只是有一个构造函数。添加无参数的构造函数只是使事情变得扑朔迷离,因为你永远不会使用它。

  • If you're using an IoC container, and this is not part of a public API, then let the container do the heavy lifting, and just have the single constructor. Adding the no-args constructor just makes things confusing, since you'll never use it.

如果这是一个公共API的一部分,那么保留两个。如果您使用的IoC,只要确保你的IoC发现了贪婪的构造函数(一个最参数)。伙计们不使用IoC的,但使用的API将AP preciate没有构建一个完整的依赖关系图,才能使用您的对象。

If this is part of a public API, then keep both. If you're using IoC, just make sure your IoC finds the "greediest" constructor (the one with the most arguments). Folks not using IoC, but using your API will appreciate not having to construct an entire dependency graph in order to use your object.

如果你不使用IoC容器,而只是想用一个模拟单元测试,保证无参数的构造函数,使贪婪的构造函数内部。添加InternalsVisibleTo为你的单元测试程序集,这样它可以使用贪婪的构造。如果你只是单元测试,那么你并不需要额外的公共API表面。

If you're not using an IoC container, but just want to to unit test with a mock, keep the no-args constructor, and make the greedy constructor internal. Add InternalsVisibleTo for your unit test assembly so that it can use the greedy constructor. If you're just unit testing, then you don't need the extra public API surface.

这篇关于构造函数注射和默认的重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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