Automapper Custom Resolver - Inject Repository into constructor
Asked Answered
A

2

5

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?

Arenicolous answered 29/9, 2010 at 21:29 Comment(0)
A
4

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

Works great now!

Arenicolous answered 29/9, 2010 at 22:12 Comment(1)
you could as well use IoC.Resolve<ISomething>() anyware in your applicationBiosynthesis
D
3

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();
    }
}
Danley answered 27/10, 2013 at 6:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.