2

I'm using ASP.NET Core, with the built-in container.

Automatic registration is done like so:

var config = new MapperConfiguration(c => c.AddProfiles(typeof(Startup)));
services.AddSingleton<IMapper>(s => config.CreateMapper());

This automatically 1) configures AutoMapper, and 2) registers all profiles found in the assembly.

But I want to register my profiles manually. How do I do that?

grokky
  • 8,537
  • 20
  • 62
  • 96
  • check this one how to configure automapper http://stackoverflow.com/questions/41220742/setting-up-automapper-5-1/41221647#41221647 – Ahmar Feb 17 '17 at 12:37

3 Answers3

5

Just use the sigular version of the method.

var config = new MapperConfiguration(c => {
    c.AddProfile<ProfileA>();
    c.AddProfile<ProfileB>();
});
services.AddSingleton<IMapper>(s => config.CreateMapper());
Tseng
  • 61,549
  • 15
  • 193
  • 205
2

You can create a new AutoMapper.MapperCOnfiguration and instead of call AddProfiles you can use the CreateMap method for each profile you want register. Something like this

var config = new AutoMapper.MapperConfiguration(cfg =>
{
    cfg.CreateMap<myObj, myObjDto>();
});

var mapper = config.CreateMapper();

Then just inject mapper and it's done.

Tinwor
  • 7,765
  • 6
  • 35
  • 56
0

I utilise Autofac for my ASP.NET Core project - here's how my code looks:

(below is the declaration of Autofac module)

public class DefaultModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        var mapperConfiguration = new MapperConfiguration(cfg => cfg.AddProfile(new AutoMapperProfileConfiguration()));
        var mapper = mapperConfiguration.CreateMapper();
        builder.Register(c => mapper).As<IMapper>().SingleInstance();
    }
}

SingleInstance() is the equivalent of AddSingleton().

AutoMapper profile:

public class AutoMapperProfileConfiguration : Profile
{
    public AutoMapperProfileConfiguration()
    {
        CreateMap<TeamDto, Team>();
    }
}

And here's how we register services:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    var containerBuilder = new ContainerBuilder();
    containerBuilder.RegisterModule<DefaultModule>();
    containerBuilder.Populate(services);
    var container = containerBuilder.Build();
    return new AutofacServiceProvider(container);
}
Alex Herman
  • 2,708
  • 4
  • 32
  • 53