如何在类型转换器中引用映射器?

时间:2016-06-07 17:56:11

标签: c# automapper

有没有办法在类型转换器中访问映射器。现在,这很糟糕,我必须做ObjectFactory.GetInstance来从StructureMap获取会话的实例。如果我能够引用mapper,我可以用它来获取实体的实例,比如mapper.Map并避免在类型转换器中使用静态方法调用。

所以这段代码

 public class AddBaseProductCommandConverter : TypeConverter<AddBaseProductService.AddBaseProduct, AddBaseProductCommand>
    {
        protected override AddBaseProductCommand ConvertCore(AddBaseProductService.AddBaseProduct source)
        {
            var session = ObjectFactory.GetNamedInstance<ISession>("PRDProd");
            var marketingPlan = session.Get<MarketingPlan>(source.BaseProductInfo.MarketingPlanId);
            var baseProductTemplate = session.Get<BaseProductTemplate>(source.BaseProductInfo.Code);
            var benefitPeriod = session.Get<BenefitPeriod>(source.BaseProductInfo.BenefitPeriodCode);
            var insuranceServiceType = session.Get<InsuranceServiceType>(source.BaseProductInfo.ServiceTypeCode);

            var command = new AddBaseProductCommand
            {
                MarketingPlan = marketingPlan,
                BaseProductTemplate = baseProductTemplate,
                BenefitPeriod = benefitPeriod,
                InsuranceServiceType = insuranceServiceType
            };

            return command;
        }
    }

可以像这样重写(我在配置阶段为NHIbernate识别的每个持久类型构建一个映射)

 public class AddBaseProductCommandConverter : TypeConverter<AddBaseProductService.AddBaseProduct, AddBaseProductCommand>
    {
        protected override AddBaseProductCommand ConvertCore(AddBaseProductService.AddBaseProduct source)
        {
            var mapper = ????

var  marketingPlan = mapper.Map<int,MarketingPlan(source.BaseProductInfo.MarketingPlanId);
            var baseProductTemplate = mapper.Map<string,BaseProductTemplate>(source.BaseProductInfo.Code);
... and so on ...
           return command;
        }
    }

1 个答案:

答案 0 :(得分:0)

您可以实施ITypeConverter而不是TypeConverter,然后使用参数context使用context.Engine.Mapper获取映射器,如下所示:

public class AddBaseProductCommandConverter : ITypeConverter<AddBaseProductService.AddBaseProduct, AddBaseProductCommand>
{
    public AddBaseProductCommand Convert(ResolutionContext context)
    {
        if (context.SourceValue == null || !(context.SourceValue is AddBaseProductService.AddBaseProduct))
            throw new AutoMapperMappingException();

        var mapper = context.Engine.Mapper;

        ...
    }
}