More About IGenericMapper and IStreamingMapper

Mendz.Library v1.2.1 introduces MapperExtensions for the IGenericMapper and IStreamingMapper interfaces. IGenericMapper and IStreamingMapper can help in creating consistent data mapping codes and strategies. MapperExtensions adds a couple of features that aim for the same.

Consider the following implementation of an IGenericMapper:

using Mendz.Library;
...
    public PersonCSVToPerson : IGenericMapper<string, Person>
    {
        public Person Map(string input, Func<Person> instance)
        {
            Person person;
            if (instance == null)
            {
                person = new Person();
            }
            else
            {
                person = instance();
            }
            ...
        }
    }
...

There's not much to it, really. However, this IGenericMapper implementation style actually inspired the creation of the IGenericMapper.Map() extension:

    public static TOutput Map<TInput, TOutput>(
        this IGenericMapper<TInput, TOutput> genericMapper, 
        TInput input) => genericMapper.Map(input, null);

This can work only if the IGenericMapper implementation would internally instantiate TOutput without relying on the Func<TOutput> instance parameter, or when it is passed as null. The explicit instantiation in the implementation makes sense for most requirements. It is actually recommended for implementors to assume that the Func<TOutput> instance parameter can be passed as null and should be evaluated accordingly.

The same idea applies to IStreamingMapper.Map() extension:

    public static IEnumerable<TOutput> Map<TInput, TOutput>(
        this IStreamingMapper<TInput, TOutput> streamingMapper, 
        IEnumerable<TInput> input) => streamingMapper.Map(input, null);

But wait, there's more! The new StreamingGenericMapperBase allows you to create streaming mappers that consume its own generic mapper. There is also a new GenericStreamingMapper which consumes a generic mapper provided to it via constructor or property dependency injection. These features are provided to reduce focus on implementing just the generic mappers, which can then be easily consumed in simple/standard streaming flows.

Give these a try! Get Mendz.Library and start having fun!

Comments