gpt4 book ai didi

c# - 泛型类的依赖注入(inject)

转载 作者:太空狗 更新时间:2023-10-29 20:12:38 26 4
gpt4 key购买 nike

我有一个通用类和一个通用接口(interface),如下所示:

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 中,我正在连接类和接口(interface)

public void ConfigureServices(IServiceCollection services)
{
services.AddTransient(typeof(IDataService<>), typeof(DataService<>));
...
}

当我尝试在我的例子中使用它时Repository.cs 始终为空。

public class Repository<T> : IRepository<T> where T : class
{
private readonly IDataService<T> _dataService;

public Repository(IDataService<T> dataService)
{
_dataService = dataService;
...
}
...
}

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

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<>));

理想情况下,这是不允许的,但由于方法接受类型作为参数,因此它没有执行任何验证就接受了它。没有人预料到有人会尝试使用它。

之所以为空,是因为 typeof(IDataService<>) !== typeof(IDataService<SomeClass>)

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

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

任何 DI 容器都会将类型 A 解析为类型 B,前提是 A 继承 B 或 A 实现 B。

在你的例子中,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));

关于c# - 泛型类的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46021991/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com