首页 > 解决方案 > 无法在 Framework 4.7.1 中初始化 AutoMapper

问题描述

By<TModel>LoginService 中的调用方法并尝试ProjectTo<TModel>给我异常映射器未初始化时。使用适当的配置调用初始化......我尝试使用services.AddAutoMapper<>NetCore,因为有工作但在 NetFramework 中找不到他。在 NetFramework 中最简单的方法是什么。我阅读了其他旧答案,但认为对我来说太复杂了。当然,我不能将此方法与 ProjectTo 一起使用,但是...

启动.cs

IServiceProvider service = ConfigureServices();
var config = new MapperConfiguration(cfg => {
    cfg.AddProfile(service.GetService<DailyReporterProfiler>());

});

private static IServiceProvider ConfigureServices()
{
    IServiceCollection services = new ServiceCollection();
    services.AddTransient<ICommandInterpreter, CommandInterpreter>();
    services.AddTransient<IValidation, Validation>();

    #region Services
    services.AddTransient<ILoginService, LoginService>();
    #endregion
    services.AddDbContext<DailyReportContext>(options =>
    options.UseSqlServer(Configuration.ConnectionString));

    services.AddSingleton<DailyReporterProfiler>();


    var result = services.BuildServiceProvider();

    return result;
}

Profiler.cs

public class DailyReporterProfiler : Profile
{
    public DailyReporterProfiler()
    {
        var configuration = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Account, AccountLoginDTO>().ReverseMap();
        });
    }
}

登录服务.cs

public class LoginService : ILoginService
{

    private DailyReportContext context;

    public LoginService(DailyReportContext context)
    {
        this.context = context;
    }

    public TModel ByUsername<TModel>(string username) => By<TModel>(u => u.Username == username)
        .SingleOrDefault();

    public string GetAccountStatus(string username)
    {
        var account = this.context.Accounts.FirstOrDefault(u => u.Username == username).Status;

        var status = Enum.GetName(typeof(AccountStatus), account);

        return status;
    }

    public void ChangePassword(int userId, string password)
    {
        throw new NotImplementedException();
    }

    public bool CheckPassword(string username, string password)
    {
        var account = context.Accounts.FirstOrDefault(u => u.Username == username);

        if (account.Password != password)
        {
            return false;
        }

        return true;
    }

    public bool Exists(string username) => ByUsername<Account>(username) != null;

    public IEnumerable<TModel> By<TModel>(Func<Account, bool> predicate)
    {
        return this.context.Accounts.Where(predicate).AsQueryable().ProjectTo<TModel>();
    }
}

标签: c#automapper

解决方案


推荐阅读