HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Generic Converter framework

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
genericframeworkconverter

Problem

I find myself frequently converting between formats, so I have come up with the following conversion framework. The converter interface surfaces a method to convert from a source type to a target type.

public interface IConverter
{
    TTarget Convert(TSource source);
}


The factory is for producing concrete converters:

public interface IConverterFactory
{
    IConverter GetConverter();
}


This next interface allows for the implementation of a generic converter that you can inject into a class and reuse for many conversions of different types (you can inject the factory instead but the code just looks cleaner with the generic converter):

public interface IGenericConverter
{
    TTarget Convert(TSource source);
}


Here's a simple example to illustrate how these interfaces are implemented. First I will look at the factory as we can provide a pretty generic factory implementation.

public class ConverterFactory : IConverterFactory
{
    private readonly Dictionary, Func> _converters =
        new Dictionary, Func>();

    public void RegisterConverter(Func constructor)
    {
        _converters.Add(new Tuple(typeof(TSource), typeof(TTarget)), constructor);
    }

    public IConverter GetConverter()
    {
        var constructor = _converters[new Tuple(typeof (TSource), typeof (TTarget))];
        return (IConverter) constructor();
    }
}


The factory implementation introduces a dictionary to keep track of registered converters and the associated constructors for the converters. A registration method is added to allow registration of converters. And finally GetConverter is implemented to look up the converter from the dictionary.

The generic converter can be implemented with a dependency on this factory like so:

```
public class GenericConverter : IGenericConverter
{
private readonly ConverterFactory _factory;

public GenericConverter(ConverterFactory factory)
{
_factory = factory;
}

public TTarget Co

Solution

I only scan read the very well written question (sorry it was late!) but:


Am I reinventing the wheel? I couldn't find anything like it in the .NET framework but I also did not look very hard.

As I understand it, yes.

I believe all you're trying to do here is to register a 'mapping' between types. Provide an instance of one type, get back another one.

Libraries such as Automapper solve this problem, by allowing you to define a mapping between types.

In your example you call converter.Convert, whereas a typical automapper configuration might call something like Mapper.Map(myType) and perform a similar role. Let me know if I've missed something, but I think that's what you're after.

Context

StackExchange Code Review Q#51889, answer score: 5

Revisions (0)

No revisions yet.