微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/csharp/244081.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐