Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Rickard Liljeberg 23 posts 114 karma points
    Mar 22, 2016 @ 09:11
    Rickard Liljeberg
    0

    Automapper Initialize from dll

    I am making a umbraco application/section in my own project. My project has it's own api controllers and model (for storing in database).

    But sometimes I want to send out a "view model" instead of my db model from my api controllers. And then I want automapper.

    So I did this piece of code to run automapper Initialize once for the dll when it loads.

    [assembly: PreApplicationStartMethod(typeof(UmbracoEventPlanner.Startup), "Start")]
    namespace UmbracoEventPlanner
    {
        public class Startup
        {
            // Automatically will work on startup
            public static void Start()
            {
                Mapper.Initialize(cfg =>
                {
                    cfg.AddProfile(new EventLocationProfile());
    
    
                });
            }
        }
    
        public class EventLocationProfile : Profile
        {
            protected override void Configure()
            {
                Mapper.CreateMap<EventLocation, EventLocationEditModel>()
                    .ForMember(dest => dest.LocationTagIds, opt => opt.Ignore());
    
            }
        }
    }
    

    I have debugged the code above and it does run like it should and after the Mapper.CreateMap has run I try this in my debugger.

    Mapper.Map<EventLocation, EventLocationEditModel>(new EventLocation(){Name="my test name"})
    

    And it works.... But later on when I run the exact same line from my API controller i get that the Mapping does not exist. At this point I can call the Mapper.CreateMap and it works but I don't want to call that from every call to my API controller.

    After googling my best bet is that it's because umbraco runs Mapper.Initialize after I do and then overwrites my mappings.

    So how can i avoid that?

    As a final note, I want my project (own dll) to be independent with it's automapper. I do not want to have to add mappings in my umbraco web project. As I want to be able to package this up and give to people.

  • Tony 105 posts 163 karma points
    Nov 25, 2019 @ 22:12
    Tony
    0

    Hi, Did you get anywhere with this? Im hitting the same issue with Automapper mappings not running in an API.

Please Sign in or register to post replies

Write your reply to:

Draft