I am getting deeper into the Dependency Injection concept and more I read, more I like the idea behind it. I have been using it for some time already, but still many things confuse me every now and then, and I feel that I am not using its full potential.
Imagine the code below. In this class, (probably a few things can be improved but..) we have one method that returns a string value. There is no need for constructor injection (or at least that's what I think, correct me if I am wrong), but then at the last line in the try block, we create new instance of the StreamReader class to be able to pass the response stream to it and to get the result using the ReadToEnd method.
The idea behind Dependency Injection is to avoid creating instances inside a class, but how to deal with this scenario?
public class WebClientService : IWebClientService
{
public async Task<String> GetApiResponseAsync(string Url)
{
String responseText = await Task.Run(() =>
{
try
{
HttpWebRequest request = WebRequest.Create(Url) as HttpWebRequest;
WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
return new StreamReader(responseStream).ReadToEnd();
}
catch (Exception e)
{
LogMessageDispatcher.Instance.Log(e);
}
return null;
});
return responseText;
}
}
I am going over 'Mark Seemann's book - Dependency Injection', but I still have a lot to cover.
The idea behind Dependency Injection is to avoid creating instances inside a class, but how to deal with this scenario?
That's not at all the point. One of the central points of DI is to enable loose coupling to Volatile Dependencies. Not all types a class depends on are volatile. Some are stable and there is no need to prevent creating stable dependencies from within a class. Chapter one of both Dependency Injection in .NET (by Mark Seemann) and its successor Dependency Injection Principles, Practices, and Patterns (by Mark and I) have a detailed description of what Volatile Dependencies and Stable Dependencies are and how they differ.
The main question you should ask is whether any of the types that WebClientService
depend on are Volatile Dependencies or not. The answer depends on your particular context, and you should be able to figure this out after (re)reading chapter 1. This chapter can be read online freely.