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:
internal class AutoHttpClient(HttpClient httpClient)
{
public async Task SendRequestAsync()
{
await httpClient.GetAsync("url");
}
}
Note that in this case httpClient
is basically a closed-over variable, and not a named private readonly field. If you want to prevent the internal code from changing the value of httpClient
after construction, you'll need to declare a separate field. But you can still initialize it from the primary constructor's parameter.
internal class AutoHttpClient(HttpClient httpClient)
{
private readonly HttpClient httpClient = httpClient;
public async Task SendRequestAsync()
{
await httpClient.GetAsync("url");
}
}
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 references httpClient
it's referencing the declared field instead.