How do you initialise a class using the C#12 primary construtor syntax. I know how to do it using dependency injection but cant find any docs showing how to do it with a normal class.
here is what I want to change to the primary constructor syntax.
internal class AutoHttpClient : IAutoHttpClient
{
private readonly HttpClient httpClient;
public AutoHttpClient()
{
httpClient = new HttpClient();
}
}
im guessing that just doing the below will not work or will it?
internal class AutoHttpClient(HttpClient httpClient) : IAutoHttpClient
{
}
I have also looked onlint but all the examples aside of DI were using base types like int etc. Thanks for the help.
Your second example works just fine:
Note that in this case
httpClientis basically a closed-over variable, and not a named private readonly field. If you want to prevent the internal code from changing the value ofhttpClientafter construction, you'll need to declare a separate field. But you can still initialize it from the primary constructor's parameter.In this case, the field overrides the variable name
httpClient, so the compiler doesn't make the closure field available in your methods: only in the field initializers. So when the method referenceshttpClientit's referencing the declared field instead.