Enabling Dependencies for a Common Class

I have a common class and a common 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;
}

Now in my StartUp.cs I connect the class and interface

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

When I try to use it in my own, for example, Repository.cs is always null.

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

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

EDIT Here is the requested repository interface and class

public interface IRepository<T> where T : class
{
    double GetCallPrice(T callEntity, Enum billingType);
    double GetCallPriceFromIdAndBillingType(int id, Enum billingType);
}

And the class 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();
        ...
    }
    ...
}
+4
source share
1 answer
services.AddTransient(typeof(IDataService<>), typeof(DataService<>));

Ideally, this should not be allowed, but since the method accepts a type parameter as a parameter, it accepted it without performing any validation. Since no one expected anyone to try to use it.

The reason it is zero is because typeof(IDataService<>) !== typeof(IDataService<SomeClass>)

https://dotnetfiddle.net/8g9Bx7

, DI- , . DI , .

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

Source: https://habr.com/ru/post/1684975/


All Articles