如何在我的服务模型中注入 AutoMapper 配置

How do I inject the AutoMapper Configuration in my Service model

我的 Asp.Net 核心有一行 API Startup.cs:

services.AddAutoMapper(Assembly.GetExecutingAssembly());

有了这个我可以使用 _mapper.Map 因为我将它注入到我的服务模型中。我正在尝试转换为使用 .ProjectTo()。它想要一个 MapperConfiguration。我该如何注入它,这样我就不必在每个方法中都创建它?

我目前的方法:

    public async Task<IEnumerable<EcommerceItemDto>> GetAllItemsUsingProjectToAsync(string customerNumber, string category = "All",
        int page = 0, int pageSize = 9999)
    {
        IQueryable<Category> categories;

        if (category == "All")
        {
            categories = _context.Categories
                .Include(c => c.Children)
                .Include(p => p.Parent)
                .AsNoTrackingWithIdentityResolution();
        }
        else
        {
            categories = _context.Categories
                .Where(n => n.Name == category)
                .Include(c => c.Children)
                .Include(p => p.Parent)
                .AsNoTrackingWithIdentityResolution();
        }

        var configuration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<EcommerceItem, EcommerceItemDto>();
                cfg.CreateMap<EcommerceItemImages, EcommerceItemImagesDto>();
                cfg.CreateMap<Category, CategoryDto>();
            });

        var dto = await _context.EcommerceItems
            .FromSqlInterpolated($"SELECT * FROM [cp].[GetEcommerceItemsView] WHERE [CustomerNumber] = {customerNumber}")
            .Include(x => x.Category)
            .Include(i => i.Images.OrderByDescending(d => d.Default))
            .OrderBy(i => i.ItemNumber)
            .Where(c => categories.Any(x => x.Children.Contains(c.Category)) || categories.Contains(c.Category))
            .Skip(page * pageSize)
            .Take(pageSize)
            .AsNoTracking()
            .ProjectTo<EcommerceItemDto>(configuration)
            .ToListAsync();

        return dto;
    }

首先,我建议您使用 Profile files 配置您的映射

public class SampleProfile : Profile
{
    public OrganizationProfile()
    {
        CreateMap<Foo, FooDto>();
        
    }
}

然后使用 IServiceCollection.AddAutoMapper() 扩展方法提供程序集后,它将扫描程序集并从配置文件中检索配置。

services.AddAutoMapper(Assembly.GetExecutingAssembly());

更多documentation here and Package Github

配置文件还有助于以更好的方式组织映射配置(在自己的文件中,而不是混淆)。

您现在可以使用

var orders = await dbContext.EcommerceItems
                       // rest of query
                       .ProjectTo<EcommerceItemDto>(_mapper.ConfigurationProvider)
                       .ToListAsync();