通过StructureMap

时间:2016-02-10 16:46:45

标签: c# automapper structuremap

这就是我目前使用的(简化并在控制台应用程序中运行):

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);

不幸的是,我在这些方面得到了例外:

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)

这可以解决(原谅双关语)。

1 个答案:

答案 0 :(得分:0)

我已经使用 StructureMap 4.0.1.318 Automapper 4.2.0.0 尝试了您的代码。

我确实得到了一个不同的异常,因为与DateTime到Int64的错误转换有关。

我认为你打算写这个:

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

通过更改类型,映射就像魅力一样。

它可能与SomeDependency类有关,它应该拥有一个无参数构造函数来解决。