如何在 .Net core 2.0 控制台应用程序中将 AutoMapper 添加到 DI [英] How to add AutoMapper to DI in .Net core 2.0 Console Application

查看:34
本文介绍了如何在 .Net core 2.0 控制台应用程序中将 AutoMapper 添加到 DI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在我的 .Net Core 2.0 控制台应用程序中使用 AutoMapper.我的班级看起来像这样:

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;
    }
    ....
}

我尝试将服务添加到 Main 方法中:

I tried to add services into Main method:

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

但是我有下一个错误'发生了一个或多个错误.(未将对象引用设置为对象的实例.)'

请告诉我如何添加 AutoMapper 以使用 DI.

Please tell me how to add AutoMapper to use DI.

推荐答案

您需要添加这个 nuget 包 AutoMapper.Extensions.Microsoft.DependencyInjection 到您的项目中,并将 AutoMapper 添加到您的 ServiceCollection

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();

这篇关于如何在 .Net core 2.0 控制台应用程序中将 AutoMapper 添加到 DI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆