c# – 泛型类的依赖注入
我有一个泛型类和这样的通用接口:
public interface IDataService<T> where T: class { IEnumerable<T> GetAll(); } public class DataService<T> : IDataService<T> where T : class { public IEnumerable<T> GetAll() { return Seed<T>.Initialize(); } } public static IEnumerable<T> Initialize() { List<T> allCalls = new List<T>(); .... return allCalls; } 现在在我的StartUp.cs中,我正在连接类和接口 public void ConfigureServices(IServiceCollection services) { services.AddTransient(typeof(IDataService<>),typeof(DataService<>)); ... } 当我尝试在我的例如Repository.cs总是为null. public class Repository<T> : IRepository<T> where T : class { private readonly IDataService<T> _dataService; public Repository(IDataService<T> dataService) { _dataService = dataService; ... } ... } 编辑 public interface IRepository<T> where T : class { double GetCallPrice(T callEntity,Enum billingType); double GetCallPriceFromIdAndBillingType(int id,Enum billingType); } 和Repository.cs类 public class Repository<T> : IRepository<T> where T : class { private readonly IDataService<T> _dataService; private IEnumerable<T> _allCalls; public Repository(IDataService<T> dataService) { _dataService = dataService; } public double GetCallPrice(int id) { _allCalls = _dataService.GetAllCalls(); ... } ... } 解决方法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<> 只有你可以使它工作的方法是为每种数据类型调用相同的方法 services.AddTransient(typeof(IDataService<Customer>),typeof(DataService<Customer>)); services.AddTransient(typeof(IDataService<Order>),typeof(DataService<Order>)); services.AddTransient(typeof(IDataService<Message>),typeof(DataService<Message>)); 要么 你可以创建一个ServiceFactory …… interface IDataServiceFactory{ DataService<T> Get<T>(); } class DataServiceFactory : IDataServiceFactory{ public DataService<T> Get<T>(){ //.. your own logic of creating DataService return new DataService<T>(); } } 并注册 services.AddTransient(typeof(IDataServiceFactory),typeof(DataServiceFactory)); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |