I have created a generic method that enables clients to specify both the concrete type of the returned instance and the actual returned type (e.g. an interface) as independent type parameters. Naturally, the concrete returned instance type parameter is constrained to inherit from the actual returned type.
The idea is that you may return an interface from the IFactory
(an object factory) Create
method. The spur for this madness was that AutoMapper needs to know which concrete type to instantiate in the factory create method, and I'd rather define the factory return value in terms of an interface.
Unfortunately you end up with quite a ridiculously long method signature.
Code:
public static TDestinationBase
MapToDomain<TSource, TDestinationBase, TDestination>
(this TSource source, IFactory<TSource, TDestinationBase> factory)
where TSource : IMappable<TDestination>, IDto
where TDestination : TDestinationBase
{
return factory.Create<TDestination>(source);
}
If anyone can understand all this, I wonder if anyone has anything they can share regarding the separation of concrete type from returned type in generic interfaces, and whether this is at all a worthwhile endeavor.