Generics dependency injection at runtime

122 views Asked by At

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

1

There are 1 answers

0
JonasH On

How do I map FileType enum class to a corresponding DTO and DTOMap object, such that on runtime I can resolve to them?

Whenever you need to map something to something else, a switch or a dictionary are often good alternatives.

Once I resolve my DTO and DTOMap object, how do I correctly call the CleanObject method using them?

One approach is to introduce a non generic interface. For example:

public interface ICleanerService{
    public bool IsValidForType(Type type);
    public Task<List<object>> CleanObject(string path);
}

This should let you resolve a list of all cleaner services, but I'm unsure how this is done in your particular DI container. Once you have a list of them you can just check each and call the right one.