Question

My existing solution has a lot of repetition like so:

config.CreateMap<IPublishedContent, ContactListingPage>()
            .ForMember(n => n.Title, map => map.ResolveUsing(AppearanceManager.GetTitle));
config.CreateMap<IPublishedContent, NewsListingPage>()
            .ForMember(n => n.Title, map => map.ResolveUsing(AppearanceManager.GetTitle));

Is there a way to remove this repetition?
I tried: using an interface:

config.CreateMap<IPublishedContent, IHaveTitle>()
            .ForMember(n => n.Title, map => map.ResolveUsing(AppearanceManager.GetTitle));

But the actual map operations need to be to the concrete types, so this mapping is not used.

Note: I'm hoping to mix and match the mappings, so all pages have titles, and some pages have promotions, etc...

I tried: Creating a custom type for title with implicit conversions to string, I think this 'would' work except for the fact that I actually need the IPublishedContent object as the input into the GetTitle method rather than the sub property PublishedProperty which it would be mapped from.

Était-ce utile?

La solution

AutoMapper doesn't try to reuse mappings by design - mostly because I would confuse myself in these cases. You opt in to shared mappings:

Mapper.Initialize(cfg => {
    cfg.CreateMap<IPublishedContent, IHaveTitle>()
        .ForMember(n => n.Title, map => map.ResolveUsing(AppearanceManager.GetTitle));

    cfg.CreateMap<IPublishedContent, ContactListingPage>()
        .IncludeBase<IPublishedContent, IHaveTitle>();
    cfg.CreateMap<IPublishedContent, NewsListingPage>()
        .IncludeBase<IPublishedContent, IHaveTitle>();
});

I'm usually pretty careful about these because I don't necessarily want to introduce coupling on the ViewModel side. I've already removed the duplication through a shared resolver.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top