Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper Custom Resolver - Inject Repository into constructor

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?

like image 492
Paul Hinett Avatar asked Sep 29 '10 21:09

Paul Hinett


2 Answers

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

Works great now!

like image 58
Paul Hinett Avatar answered Sep 28 '22 07:09

Paul Hinett


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();
    }
}
like image 22
Leniel Maccaferri Avatar answered Sep 28 '22 08:09

Leniel Maccaferri