1
votes

This is what I am currently using (simplified and run in console app):

public class SomeValueResolver : ValueResolver<DateTime, long> 
{
    private readonly ISomeDependency _someDependency;

    public SomeValueResolver(ISomeDependency _someDependency)
    {
        // ...
    }

    protected override long ResolveCore(DateTime source)
    {
        // ...
    }
}

public class MyRegistry : Registry
{
    public MyRegistry()
    {
        For<ISomeDependency >()
        .Singleton()
        .Use<SomeDependency>();
    }
}

public static class AutoMapperConfiguration
{
    public static void Configure(IContainer container)
    {
        Mapper.Initialize(cfg =>
        {
        cfg.ConstructServicesUsing(t => container.GetInstance(t));
        cfg.AddProfile(new AutomapperProfile1());
        });
    }
}

public class AutomapperProfile1 : Profile
{
    protected override void Configure()
    {
        CreateMap<Source, Target>()
        .ForMember(dest => dest.Y, opt => opt.ResolveUsing<SomeValueResolver>().FromMember(e => e.X))
        .IgnoreAllSourcePropertiesWithAnInaccessibleSetter();
    }
}

public class Source
{
    public DateTime X { get; set; }
}

public class Target
{
    public DateTime Y { get; set; }
}


// main method
var container1 = new Container(new MyRegistry());
AutoMapperConfiguration.Configure(container1);
var source = new Source { X = DateTime.UtcNow };
var target = Mapper.Map<Target>(source);

Unfortunately, I get an exception along those lines:

Unable to create a build plan for concrete type SomeValueResolver

new SomeValueResolver(ISomeDependency)
  ? ISomeDependency= **Default**

1.) Attempting to create a BuildPlan for Instance of SomeValueResolver -- SomeValueResolver
2.) Container.GetInstance(SomeValueResolver)

Can this be resolved (pardon the pun).

1
Could you specify the version of Automapper/StrutureMap you use ? - Fab
The latest via nuget. - cs0815

1 Answers

0
votes

I've tried your code with StructureMap 4.0.1.318 and Automapper 4.2.0.0.

I did get an exception which is different because related to bad conversion of DateTime to Int64.

I think you intended to write this :

public class Target
{
    public long Y { get; set; }
}

By changing the type, the mapping works like a charm.

It's maybe related to the SomeDependency class which should possess a parameterless constructor to be resolved that way.