如何在 asp.net core 6.0 的 Program.cs 中添加 AutoMapperConfiguration?
我试过了
程序.cs
var builder = WebApplication.CreateBuilder(args);
// Auto Mapper Configurations
builder.Services.AddAutoMapper(typeof(Automapper)); // Automapper is my Automapper class name
但是我在调试时遇到了这个错误
Exception has occurred: CLR/System.InvalidOperationException
An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.AspNetCore.dll: 'Cannot modify ServiceCollection after application is built.'
at Microsoft.AspNetCore.WebApplicationServiceCollection.CheckServicesAccess()
at Microsoft.AspNetCore.WebApplicationServiceCollection.Add(ServiceDescriptor item)
at Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(IServiceCollection services, Type serviceType, Object implementationInstance)
at Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton[TService](IServiceCollection services, TService implementationInstance)
at Microsoft.Extensions.DependencyInjection.OptionsServiceCollectionExtensions.Configure[TOptions](IServiceCollection services, String name, Action`1 configureOptions)
at Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddAutoMapperClasses(IServiceCollection services, Action`2 configAction, IEnumerable`1 assembliesToScan, ServiceLifetime serviceLifetime)
at Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.AddAutoMapper(IServiceCollection services, Type[] profileAssemblyMarkerTypes)
at Program.<Main>$(String[] args) in in PaymentApi/Program.cs:line 42
Automapper.cs
using AutoMapper;
using TechnePaymentApi.Models;
namespace TechnePaymentApi.Utilities;
public class Automapper : Profile
{
public Automapper() {
CreateMap<PaymentRequest, PaymentRequestViewModel>();
CreateMap<Payment, PaymentViewModel>();
}
}