Injection parameter to automatically configure ValueResolver Automapper using Ninject

I use the library automapperto convert mine Modelto my ViewModel. For each ModelI create a profile, inside which I add my cards using CreateMap.

I want to use a custom ValueResolverone in which it will get the registered user id from IContext, so I need to pass the implementation IContextusing Ninject.

Inside my profile class:

Mapper.CreateMap<ViewModel, BusinessModel>()
.ForMember(dest => dest.ManagerId, opt => opt.ResolveUsing<GetManagerResolver>());

Then mine GetManagerResolver:

public class GetManagerResolver : ValueResolver<BusinessModel, int>
{
    private IContext context;
    public GetManagerResolver(IContext context)
    {
        this.context = context;
    }

    protected override int GetManagerResolver(BusinessModel source)
    {
        return context.UserId;
    }
}

But I get this exception message {"Type needs to have a constructor with 0 args or only optional args\r\nParameter name: type"}.

Any ideas on how to get automapper to use ninject to create an object?

UPDATE My code for adding automapper configuration:

public static class AutoMapperWebConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(cfg =>
        {            
            cfg.AddProfile(new Profile1());         
            cfg.AddProfile(new Profile2());

            // now i want to add this line, but how to get access to kernel in static class?
            // cfg.ConstructServicesUsing(t => Kernel.Get(t));
        });
    }
}
+4
2

ConstructedBy , Automapper GetManagerResolver ResolveUsing:

Mapper.CreateMap<ViewModel, BusinessModel>()
    .ForMember(dest => dest.ManagerId, 
         opt => opt.ResolveUsing<GetManagerResolver>()
                   .ConstructedBy(() => kernel.Get<GetManagerResolver>());

​​Ninject, Automapper Mapper.Configuration.ConstructServicesUsing:

Mapper.Configuration.ConstructServicesUsing((type) => kernel.Get(type));
+6

NinjectModule Automapper, automapper automapper Ninject Kernel . :

public class AutoMapperModule : NinjectModule
{
    public override void Load()
    {
        Mapper.Initialize(cfg =>
        {
            cfg.ConstructServicesUsing(t => Kernel.Get(t));

            cfg.AddProfile(new Profile1());
            cfg.AddProfile(new Profile2());
        });
    }
}
+3

Source: https://habr.com/ru/post/1546585/


All Articles