无法在Framework 4.7.1中初始化AutoMapper

时间:2018-08-18 12:58:34

标签: c# automapper

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

Startup.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();
        });
    }
}

LoginService.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>();
    }
}

0 个答案:

没有答案