Skip to content

Instantly share code, notes, and snippets.

@mr5z
Last active October 1, 2022 13:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mr5z/7a72471eef039093c0046a2915f0ccda to your computer and use it in GitHub Desktop.
Save mr5z/7a72471eef039093c0046a2915f0ccda to your computer and use it in GitHub Desktop.
mapper
using System;
using System.Collections.Generic;
using ParameterizedFunc = System.Func<object, object>;
namespace CompanyName.Helpers
{
public class Mapper
{
private readonly IDictionary<(Type, Type), ParameterizedFunc> objectDictionary =
new Dictionary<(Type, Type), ParameterizedFunc>();
public void Register<TSource, TDestination>(Func<TSource, TDestination> mapping)
where TSource : class
where TDestination : class
{
var key = ToKey<TSource, TDestination>();
objectDictionary[key] = (arg) => mapping((TSource)arg);
}
public TDestination Map<TSource, TDestination>(TSource source)
where TSource : class
where TDestination : class
{
var key = ToKey<TSource, TDestination>();
return (TDestination)objectDictionary[key](source);
}
private (Type, Type) ToKey<TSource, TDestination>()
{
return (typeof(TSource), typeof(TDestination));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment