我正在一个控制台应用程序上工作,我想获得一个通用服务类型的实例。这是我的实现它给我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
我想实现通用服务,我将传递任何服务,它将给出实例。
您在构建IServiceProvider
之后向集合添加服务,因此它不会知道这个新添加的服务的任何信息,您需要在构建提供者之前添加服务:
public class HelperService
{
private readonly ServiceCollection collection;
private readonly IServiceProvider serviceProvider;
public HelperService()
{
collection = new ServiceCollection();
#region [register Services]
collection.AddScoped<ICustomerService, CustomerService>();
#endregion
serviceProvider = collection.BuildServiceProvider();
}
public T? GetServiceInstance<T>() where T : class
{
return serviceProvider.GetService<T>();
}
}
同时?? null
也没有多大意义,可以移除。
总的来说,我想说这样的包装器不是很有用,至少基于所提供的代码。