Reputation: 318
Imagine the following constuctor
public RestClient(
string key,
Uri baseAddress,
IHttpClient httpClient,
ISerializer serializer,
IResponseFactory responseFactory)
{
_key = key;
_baseAddress = baseAddress;
_httpClient = httpClient;
_serializer = serializer;
_responseFactory = responseFactory;
}
When is it appropriate to create a local default like this?
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;}
and allowing the dependency of IHttpClient to be overridden using property injection.
Or is it the responsibility of the consumer to pass the dependency in the constructor and not rely on local defaults at all? Mark Seemann, in his book describes that property injection is appropriate when there is a good local default but I am struggling in this example to decide whether or not it is appropriate to use a local default in the first place.
Upvotes: 0
Views: 75
Reputation: 1097
I would never have local defaults like that, as it is a pain to unit test.
If you would like to simplify instantiation of the class, using the default class, then I would go instead with an constructor override like this:
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;}
Upvotes: 0