i am using automapper to map from dtos to domain and vice versa; i am using custom type converter to do the conversion but i want to inject dependencies into my converter class using simple injector ioc; i can't do that. please tell me how to achieve that?
public class DtoToEntityConverter : ITypeConverter<Dto, Entity>
{
private readonly IEntityRepository _entityRepository;
public DtoToEntityConverter (IEntityRepository entityRepository )
{
_entityRepository = entityRepository ;
}
public Entity Convert(ResolutionContext context)
{
}
}
You'll need to configure services via AutoMapper:
var container = ConfigureSimpleInjectorContainer();
Mapper.Initialize(cfg => {
cfg.ConstructServicesUsing(type => container.GetInstance(type));
// The rest of your initialization
});
I used this approach every time my container cannot reach some of my code like the question you posted.
public class DtoToEntityConverter : ITypeConverter<Dto, Entity>
{
private readonly IEntityRepository _entityRepository;
public DtoToEntityConverter (IEntityRepository entityRepository )
{
_entityRepository = entityRepository ;
}
public Entity Convert(ResolutionContext context)
{
}
}
How would you register it:
Mapper.CreateMap<From, To>().ConvertUsing(new DtoToEntityConverter(Ioc.Resolve<IEntityRepository>()));
The Ioc static class should hold the IUnitContainer where you register all your dependency.
public static class IoC
{
public static IUnityContainer Unity { get; private set; }
public static T Resolve<T>()
{
return Unity.Resolve<T>();
}
public static T Resolve<T>(string key)
{
return Unity.Resolve<T>(key);
}
public static void Initialize(IUnityContainer unity)
{
Unity = unity;
}
}
Note : Make it sure that you already created the UnityContainer prior of mapping. Your problem is not typical and you may consider to redesigning it and leave the mapping (Automapper) for mapping of model to model only. But may be in some point you have weird requirement you can consider this approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With