【问题标题】:Generics dependency injection at runtime运行时的泛型依赖注入
【发布时间】:2022-12-04 11:16:26
【问题描述】:

For starters, I am new to dotnet and generics, so bear with me if the question is a bit unclear. So I have an interface which I have defined something along the lines of:

public interface ICleanerService<T, V> 
{
    public Task<List<T>> CleanObject(string path);
}

I also register it in the startup using:

services.AddScoped<ICleanerService<DTO, DTOMap>,
    CleanerService<DTO, DTOMap>>();

services.AddScoped<ICleanerService<DTO2, DTO2Map>,
    CleanerService<DTO2, DTO2Map>>();

Now, I have another service where I have to figure out which DTO object to use at runtime, and then correspondingly call the CleanObject method on that

public class ExcelService : IExcelService 
{


      public async Task<bool> TransformExcel(FileType fileType) 
      {
          // TODO: Using the fileType, I want to be able to figure out the corresponding DTO and DTOMap
          // Once I have the correct DTO and DTOMap objects, I want to call the ICleanerService<DTO, DTOMap>.CleanObject(string path) method on it

      }

So I have two questions:

  1. How do I map FileType enum class to a corresponding DTO and DTOMap object, such that on runtime I can resolve to them?
  2. Once I resolve my DTO and DTOMap object, how do I correctly call the CleanObject method using them?

I tried fiddling around using custom injections such that I can resolve using:

services.AddScoped<IDTO, DTO>(FileType.SMALL_EXCEL.ToString());

But this seems overkill since it seems incorrect to have an interface associated to a DTO class

    标签: c# .net generics .net-3.0


    【解决方案1】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    相关资源
    最近更新 更多