c# – 泛型类的依赖注入

前端之家收集整理的这篇文章主要介绍了c# – 泛型类的依赖注入前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个泛型类和这样的通用接口:
  1. public interface IDataService<T> where T: class
  2. {
  3. IEnumerable<T> GetAll();
  4. }
  5.  
  6. public class DataService<T> : IDataService<T> where T : class
  7. {
  8. public IEnumerable<T> GetAll()
  9. {
  10. return Seed<T>.Initialize();
  11. }
  12. }
  13.  
  14. public static IEnumerable<T> Initialize()
  15. {
  16. List<T> allCalls = new List<T>();
  17. ....
  18. return allCalls;
  19. }

现在在我的StartUp.cs中,我正在连接类和接口

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddTransient(typeof(IDataService<>),typeof(DataService<>));
  4. ...
  5. }

当我尝试在我的例如Repository.cs总是为null.

  1. public class Repository<T> : IRepository<T> where T : class
  2. {
  3. private readonly IDataService<T> _dataService;
  4.  
  5. public Repository(IDataService<T> dataService)
  6. {
  7. _dataService = dataService;
  8. ...
  9. }
  10. ...
  11. }

编辑
这是请求的存储库接口和类

  1. public interface IRepository<T> where T : class
  2. {
  3. double GetCallPrice(T callEntity,Enum billingType);
  4. double GetCallPriceFromIdAndBillingType(int id,Enum billingType);
  5. }

和Repository.cs类

  1. public class Repository<T> : IRepository<T> where T : class
  2. {
  3. private readonly IDataService<T> _dataService;
  4. private IEnumerable<T> _allCalls;
  5.  
  6. public Repository(IDataService<T> dataService)
  7. {
  8. _dataService = dataService;
  9. }
  10.  
  11. public double GetCallPrice(int id)
  12. {
  13. _allCalls = _dataService.GetAllCalls();
  14. ...
  15. }
  16. ...
  17. }

解决方法

  1. services.AddTransient(typeof(IDataService<>),typeof(DataService<>));

理想情况下,不应该允许这样做,但是当方法接受type作为参数时,它会在不执行任何验证的情况下接受它.没有人希望有人会尝试使用它.

它为null的原因,因为typeof(IDataService<>)!== typeof(IDataService< SomeClass>)

您可以在https://dotnetfiddle.net/8g9Bx7查看示例

这就是原因,DI解析器永远不会知道如何解决.大多数DI容器仅在类型实现请求的接口或具有基类作为请求的类时解析类型.

只有当A继承B或A实现B时,任何DI容器都将解析类型B的类型A.

在您的情况下,DataService<>实现IDataService<>,但DataService< T>没有实现IDataService<>

只有你可以使它工作的方法是为每种数据类型调用相同的方法

  1. services.AddTransient(typeof(IDataService<Customer>),typeof(DataService<Customer>));
  2.  
  3. services.AddTransient(typeof(IDataService<Order>),typeof(DataService<Order>));
  4.  
  5. services.AddTransient(typeof(IDataService<Message>),typeof(DataService<Message>));

要么

你可以创建一个ServiceFactory ……

  1. interface IDataServiceFactory{
  2. DataService<T> Get<T>();
  3. }
  4.  
  5. class DataServiceFactory : IDataServiceFactory{
  6. public DataService<T> Get<T>(){
  7. //.. your own logic of creating DataService
  8.  
  9. return new DataService<T>();
  10. }
  11. }

注册

  1. services.AddTransient(typeof(IDataServiceFactory),typeof(DataServiceFactory));

猜你在找的C#相关文章