如何将值传递给自定义ValueResolver?

时间:2012-02-15 16:11:30

标签: c# automapper

我正在努力将值传递给自定义ValueResolver。我基本上试图根据我的ViewModel将Int转换为Object。但是,我无法让它将值传递给我的ValueResolver

我有以下自定义ValueResolver:

public class CustomResolver : ValueResolver<CreateContainerViewModel, Container>
{ 
    private int id = 0;

    public CustomResolver(int? sourceId)
    {
        if(sourceId.HasValue)
            id = sourceId.Value;
    }
    protected override Container ResolveCore(CreateContainerViewModel source)
    {
        if (id == 0) return null;
        else
        {
            ISession _session = DependencyResolver.Current.GetService<ISessionFactory>().GetCurrentSession();
            return _session.Get<Container>(id);
        }
    }
}

当我使用硬编码的int创建地图时,它可以正常工作,如下面的代码

Mapper.CreateMap<CreateContainerViewModel, Container>()
.ForMember(a => a.CurrentContainer, opt => opt.ResolveUsing(src => new CustomResolver(33)));

但是当我尝试从我的viewmodel获取值时,它无效(抛出映射异常)

Mapper.CreateMap<CreateContainerViewModel, Container>()
            .ForMember(dest => dest.CurrentContainer, opt => opt.MapFrom(src => new CustomResolver(src.CurrentContainerId)));

有人能指出我将值传递给自定义ValueResolver的正确语法吗?

由于

更新:

基本上尝试写这样的东西:

  public class IdToObjectResolver<T> : ValueResolver<int, T> where T : class
{ 
    private ISession _session;
    private int id;
    public IdToObjectResolver(Nullable<int> sourceId)
    {
        _session = DependencyResolver.Current.GetService<ISessionFactory>().GetCurrentSession();
        if(sourceId.HasValue)
            id = sourceId.Value;
    }

    protected override T ResolveCore(int source)
    {
        return _session.Get<T>(source);
    }
}

这段代码目前没有意义,但只是想尝试传递int ...

1 个答案:

答案 0 :(得分:1)

如果我理解正确,我认为你可能会过度使ValueResolver复杂化。如您所见,整个CreateContainerViewModel类是在ValueResolver中的ResolveCore方法中发送的。这将是具有值的整个源对象。

因此,您应该能够使用此映射从源对象中提取id值:opt.ResolveUsing(src => new CustomResolver())。 (没有构造函数arg)。

希望这有帮助。

修改

我的测试:

        [TestMethod]
        public void TestMethod1()
        {
            Mapper.CreateMap<CreateContainerViewModel, Container>()
                .ForMember(a => a.CurrentContainer, opt => opt.ResolveUsing<CustomResolver>());


            var source = new CreateContainerViewModel()
            {
                ID = 3
            };

            var destination = new Container();

            Mapper.Map(source, destination);

            Assert.AreEqual(destination.CurrentContainer.ID, 3);

        }

CustomResolver:

public class CustomResolver : ValueResolver<CreateContainerViewModel, Container>
{
    protected override Container ResolveCore(CreateContainerViewModel source)
    {

            return new Container() { ID = source.ID };  
    }
}