c# - 无法在 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>();
}
}
解决方案
推荐阅读
- python - 在使用 Pylint 的“def”之后,多个空格没有错误的空格警告?
- c# - 如何使我的应用程序的特定文件夹出现在图库中?
- swift - TextField .textContentType 修饰符在 SwiftUI 中无效
- php - 循环来自 API 的大量数据并导入 WordPress 的最有效方法?
- node.js - 如何解决“TypeError:process.getuid 不是函数”
- c# - 如何在 c# 中优化我的 zip 函数以更快?
- reactjs - 这个 react-bootstrap 轮播组件有什么问题?
- javascript - 无效的日期 JS 时间戳 2checkout 响应
- c - 如何在不使用临时节点的情况下为 root 添加值?
- ojalgo - 如何使用 ojalgo 金融的 Markovitz 模型