I’m trying to find a nice way to do dependency injection with a list of interfaces. I have multiple “parsers”, where each type of parser can handle parsing multiple files specific for that parser.
For example, I have the following class and interface structure.
Let me explain what I have going on…… I have multiple parsers (let’s call them ParserA, ParserB, etc). Each parser is associated with multiple files specific to that parser. In this example, let’s call them (ParserAFile1, ParserAFile2, etc)
To make this work, I had to create empty interfaces for the file specific parsers, to get the DI to work with the top level parser. Ex: empty interfaces for IParserAFile1, IParserAFile2. This seems like bad practice, but, can’t figure out any other way to achieve these results with DI.
Can anyone offer any suggestions? Ideally, I’d also like the ParserA constructor to accept an IEnumerable of files { IParserAFile1, IParserAFile2 } in case the need arises for additional files in the future.
ParserA is just responsible for essentially reading the contents of the files it receives and persists to a database. There is no need to expose these as properties to the outside world.
public ParserA(IParserAFile1, IParserAFile2) : IParserA
{
}
public interface IParserA : IParser
{
}
public interface IParserAFile1 : IParser)
{
}
public interface IParserAFile2 : IParser)
{
}
public class ParserAFile1 : IParserAFile1)
{
}
public class ParserAFile2 : IParserAFile2)
{
}
In my program.cs, I register dependencies:
services.AddScoped<IParserA, ParserA>;
services.AddScoped<IParserAFile1, ParserAFile1>;
services.AddScoped<IParserAFile2, ParserAFile2>;
The code works as above, but I’m looking for a more elegant solution
William Shaya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.