Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper inject dependencies into custom type converter using Simple injector (Ioc)

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)
    {

    }     


}
like image 884
yo2011 Avatar asked Oct 17 '25 10:10

yo2011


2 Answers

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
});
like image 139
Jimmy Bogard Avatar answered Oct 19 '25 06:10

Jimmy Bogard


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.

like image 34
jtabuloc Avatar answered Oct 19 '25 06:10

jtabuloc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!