I have the following pattern:
An interface for serializing files, called IFileSerializer, which has multiple concrete implementations. Not every serializer can handle every file type, so we need to tell the application to know which one to use.
I also have a type from which all files that can be serialized extend from, let's call it IStorableFile. I have a requirement to use a different concrete implementation of IFileSerializer based on the type of IStorableFile.
Currently, I solve this problem by using a static factory class with a Build() method that accepts a file type and returns the appropriate serializer, but I'd rather do it using dependency injection.
What I'd ideally like is to be able to register different file types to use different serializer implementations.
The ultimate goal here is for the class injecting a serializer to be able to do something like this with DI:
public class MyConsumingClass
{
// DI will inject these, and will know what concrete implementation of serializer to use.
public MyConsumingClass(
IFileSerializer<FileTypeA> serializerForTypeA,
IFileSerializer<FileTypeB> serializerForTypeB)
{
// TODO use the serializers in the class
}
}
I'd also like to throw a nice error if you try to inject a serializer for a file type that has not been registered. How can I accomplish something like this? I'm not really sure what to call this pattern in order to search it up, but I know I've seen stuff like this before in .NET.