Randy
Randy

Reputation: 1287

How do I inject the AutoMapper Configuration in my Service model

I have a line in my Asp.Net Core API Startup.cs:

services.AddAutoMapper(Assembly.GetExecutingAssembly());

With this I can use _mapper.Map because I inject it into my Service model. I am trying to convert to use .ProjectTo(). It wants a MapperConfiguration. How do I inject that so I don't have to create it in every method?

My current method:

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

Upvotes: 0

Views: 594

Answers (1)

Anu Viswan
Anu Viswan

Reputation: 18153

To begin with, I would suggest you use Profile files to configure your mappings.

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

And then using the once you provide the Assembly using the IServiceCollection.AddAutoMapper() extension method, it would scan through the assembly and retrieve configurations from the Profile files.

services.AddAutoMapper(Assembly.GetExecutingAssembly());

More documentation and Package Github

Profile file also helps to organize the mapping configurations in a better way (in own files, than mixing things up).

You could now use,

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

Upvotes: 4

Related Questions