I am working on a console application where I want to get the instance of a generic service type. Here is my implementation it gives me null.
public class HelperService
{
private readonly ServiceCollection collection;
private readonly IServiceProvider serviceProvider;
public HelperService()
{
collection = new ServiceCollection();
serviceProvider = collection.BuildServiceProvider();
}
public void RegisterService()
{
#region [register Services]
collection.AddScoped<ICustomerService, CustomerService>();
#endregion
}
public T? GetServiceInstance<T>() where T : class
{
return serviceProvider.GetService<T>()?? null;
}
}
var helperService = new HelperService();
helperService.RegisterService();
var result = helperService.GetServiceInstance<ICustomerService>(); // result is null
I want to implement generic service to which I will pass any service and it will give instance.