Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add AutoMapper to DI in .Net core 2.0 Console Application

I try to use AutoMapper in my .Net Core 2.0 Console Application. My class looks like this:

public class AutoGetCurrency
{
    private readonly IMapper mapper;
    public AutoGetCurrency(IMapper mapper) {
    this.mapper = mapper;
    }
    ....
}

I tried to add services into Main method:

static void Main(string[] args)
{
    var services = new ServiceCollection();
    ServiceProvider = services.BuildServiceProvider();
    services.AddTransient<IMapper>();
    ....
}

But I have the next error 'One or more errors occurred. (Object reference not set to an instance of an object.)'

Please tell me how to add AutoMapper to use DI.

like image 643
Uladz Kha Avatar asked Dec 07 '22 15:12

Uladz Kha


1 Answers

You need to add this nuget package AutoMapper.Extensions.Microsoft.DependencyInjection to your project and add AutoMapper to your ServiceCollection like this

var services = new ServiceCollection();
services.AddAutoMapper(mapperConfig => mapperConfig.AddProfiles(GetType().Assembly))
ServiceProvider = services.BuildServiceProvider();
like image 60
Kahbazi Avatar answered Jan 12 '23 08:01

Kahbazi