I guess you´re confused that the value is set in the constructor instead where you declare the field. In your example you could easily and probably also validly write the following:
private readonly IHostingEnvironment _hostingEnvironment = new HostingEnvironment();
This will have exactly the same effect, as it is implicitly converted to a constructor-statement by the compiler. So both are similar.
However there exists a need to use the constructor when you don´t know the value to be used at compile-time. Imagine the constructor of HostingEnvironment
expects an integer to be passed:
public class WebHostBuilder
{
private readonly IHostingEnvironment _hostingEnvironment // = new HostingEnvironment(whatToSetHere ???);
public WebHostBuilder(int i)
{
_hostingEnvironment = new HostingEnvironment(i);
}
}
During compile-time you don´t know the value to be provided for the HostingEnvironment
-constructor. So you provide it as early as you get it, in this case in the constructor of your own class.
In addition the readonly
-modifier simply states that you can set the value for a member only within the constructor (or in place with the declaration, which is converted to a constructor-call, remember what I´ve mentioned above).