This is usually done in the same way that Dryushkin avoided. You will need to register your open generic type with your container. With StructureMap, it would be something like this:
Scan(scanner => { scanner.TheCallingAssembly(); scanner.ConnectImplementationsToTypesClosing(typeof (IValueConverter<>)); });
In Autofac, it will be something like this:
builder.RegisterGeneric(typeof(IValueConverter<>));
Then you will create your general type for the solution:
Type openType = typeof(IValueConverter<>); Type closedType = openType.MakeGenericType(type); var instance = container.Resolve(closedType);
I donโt think you want your factory method parameter to be generic. It just needs to be a simple type:
public IValueConverter<T> Create<T>(Type type) {
Instead of creating all this, why not just use Automapper? Here are the types of mappings that I usually create:
public class DateTimeToDateMapping : IAutoMapperInitializer { public void Initialize(IConfiguration configuration) { configuration.CreateMap<DateTime, Date>().ConstructUsing( dateTime => new Date(dateTime.Year, dateTime.Month, dateTime.Day)); } }
Here's how to use this mapping:
var date = _mappingEngine.Map<DateTime, Date>(DateTime.Today);
I donโt know that I used System.Convert a lot, but it doesnโt seem like a hint of intent, and I guess itโs hard to know how to convert from certain things. If you use Automapper, you can also easily check your mappings.