Automapper Custom Resolver - Inject Repository int

2020-04-06 16:17发布

I am trying to create a custom resolver for automapper which needs to access one of my data repositories to retreive the logged in users account.

Here is my code so far...

public class FollowingResolver : ValueResolver<Audio, bool>
    {
        readonly IIdentityTasks identityTasks;

        public FollowingResolver(IIdentityTasks identitTasks)
        {
            this.identityTasks = identitTasks;
        }

        protected override bool ResolveCore(Audio source)
        {
            var user = identityTasks.GetCurrentIdentity();
            if (user != null)
                return user.IsFollowingUser(source.DJAccount);

            return false;
        }
    }

However I am getting this error:

FollowingResolver' does not have a default constructor

I have tried adding a default contrstructor but my repository never gets initialised then.

This is my autoampper initialisation code:

public static void Configure(IWindsorContainer container)
        {
            Mapper.Reset();
            Mapper.Initialize(x =>
            {
                x.AddProfile<AccountProfile>();
                x.AddProfile<AudioProfile>();
                x.ConstructServicesUsing(container.Resolve);
            });

            Mapper.AssertConfigurationIsValid();
        }

Am I missing something, is it even possible to do it like this or am I missing the boat here?

2条回答
戒情不戒烟
2楼-- · 2020-04-06 16:29

Found the solution shorlty after...i was forgetting to add my resolvers as an IoC container.

Works great now!

查看更多
放我归山
3楼-- · 2020-04-06 16:51

I was getting the same error using Castle Windsor while trying to inject a service.

I had to add:

Mapper.Initialize(map =>
{
    map.ConstructServicesUsing(_container.Resolve);
});

before Mapper.CreateMap calls.

Created a ValueResolverInstaller like this:

public class ValueResolverInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
                                .BasedOn<IValueResolver>()
                                .LifestyleTransient());
    }
}

and the ValueResolver itself:

public class DivergencesResolver : ValueResolver<MyClass, int>
{
    private AssessmentService assessmentService;

    public DivergencesResolver(AssessmentService assessmentService)
    {
        this.assessmentService = assessmentService;
    }

    protected override int ResolveCore(MyClass c)
    {
        return assessmentService.GetAssessmentDivergences(c.AssessmentId).Count();
    }
}
查看更多
登录 后发表回答