何时在依赖依赖注入的类中使用本地默认值是合适的

时间:2018-04-04 21:38:39

标签: c# dependency-injection property-injection

想象一下以下的构造函数

public RestClient(
    string key,
    Uri baseAddress,
    IHttpClient httpClient,
    ISerializer serializer,
    IResponseFactory responseFactory)
{
    _key = key;

    _baseAddress = baseAddress;
    _httpClient = httpClient;
    _serializer = serializer;
    _responseFactory = responseFactory;
}

何时适合创建这样的本地默认值?

public RestClient(
    string key,
    Uri baseAddress,
    IHttpClient httpClient,
    ISerializer serializer,
    IResponseFactory responseFactory)
{
    _key = key;

    _baseAddress = baseAddress;
    _serializer = serializer;
    _responseFactory = responseFactory;

    HttpClient = new HttpClientAdapter();
}

IHttpClient HttpClient {get; set;}

并允许使用属性注入覆盖IHttpClient的依赖项。

或者消费者有责任在构造函数中传递依赖项而不依赖于本地默认值吗? Mark Seemann在他的书中描述了当有一个良好的局部默认值时,属性注入是合适的,但我在这个例子中努力决定是否适合首先使用本地默认值。

1 个答案:

答案 0 :(得分:0)

我永远不会有像这样的本地默认值,因为单元测试很难。

如果你想简化类的实例化,使用默认类,那么我会改为使用这样的构造函数覆盖:

public RestClient(
    string key,
    Uri baseAddress,
    ISerializer serializer,
    IResponseFactory responseFactory)
    : this(key, baseAddress, new HttpClientAdapter(), serializer, responseFactory)
{
}

public RestClient(
    string key,
    Uri baseAddress,
    IHttpClient httpClient,
    ISerializer serializer,
    IResponseFactory responseFactory)
{
    _key = key;

    _baseAddress = baseAddress;
    _serializer = serializer;
    _responseFactory = responseFactory;

    HttpClient = httpClient;
}

IHttpClient HttpClient {get; private set;}