I want to give parameters when injecting generic types. Is this possible?
My generic type definition:
public interface IApiClient<T> where T : class
{
}
public class ApiClient<T> : IApiClient<T> where T : class
{
public ApiClient(string baseAddress = "", string endpoint = "")
{
//some codes
}
}
My implementation is:
services.AddSingleton(typeof(IApiClient<>), typeof(ApiClient<>));
How do I give baseAddress
and endpoint
in this usage?
Thanks.
CodePudding user response:
You can make separate class for the constructor parameters.
For example based on your code:
public class ApiClientSettings
{
public string BaseAddress { get; set; }
public string Endpoint { get; set; }
}
Create an instance of the ApiClientSettings
(or even you can simply get values from appsettings.json
file). Then register ApiClientSettings
in the container.
var apiClientSettings = new ApiClientSettings
{
BaseAddress = "address",
Endpoint = "endpoint"
};
services.AddSingleton(apiClientSettings);
Inject settings class to your ApiClient
public class ApiClient<T> : IApiClient<T> where T : class
{
public ApiClient(ApiClientSettings settings)
{
//some codes
}
}