Copied to clipboard

Flag this post as spam?

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


  • Peter Laurie 3 posts 73 karma points
    1 week ago
    Peter Laurie
    0

    Umbraco 8 Custom core Mappers

    Hi, I have been looking for any documentation on add my own custom mappers (using AutoMapper into Umbraco 8 on start up.

    I tried the following code, but the error I got back was that AutoMapper can only be initialised once.

    public class AutoMapperComponent : IComponent
      {
        // initialize: runs once when Umbraco starts
        public void Initialize()
        {
          InitAutoMapper();
        }
    
        public void InitAutoMapper()
        {
          Mapper.Initialize(cfg => cfg.CreateMap<CmtRestOptions, CmtRestConfig>());
        }
    
        // terminate: runs once when Umbraco stops
        public void Terminate()
        {
        }
      }
    

    I have then come across the following code by looking at what is exposed by composition in Visual Studio, and came across AddCoreMappers

     [RuntimeLevel(MinLevel = RuntimeLevel.Run)]
      public class ApplicationStartUp : IUserComposer
      {
        public void Compose(Composition composition)
        {
          // Append our component to the collection of Components
          // It will be the last one to be run
          composition.Mappers().AddCoreMappers<AutoMapperComponent>(); // look into add core mappers
        }
      }
    

    So far I have found no documantation on implementing my own Maps using this function.

    If anyone has any information concerning this, or pointers in the right direction, that would be most welcome.

    Kind regards, Peter

  • Kevin Jump 1339 posts 8302 karma points MVP 2x c-trib
    1 week ago
    Kevin Jump
    0

    Hi Peter,

    Along with the Umbraco Updated AutoMapper has been upgraded to the latest v8 version and that has changed things a little.

    the prescribed way to add mappers appears to be to use a profile class

    eg :

    internal class MyCustomProfile : Profile
    {
        public MyCustomProfile()
        {
            // dto -> model 
            CreateMap<MyCustomModelDto, MyCustomModel>();
    
            // model -> dto
            CreateMap<MyCustomModel, MyCustomModelDto>();
        }
    }
    

    these profiles define the mappings for you and then you register the profile in your composer.

    composition.Register<Profile, MyCustomProfile>();
    

    this will then let you use Mapper.Map across your code. as before.

Please Sign in or register to post replies

Write your reply to:

Draft