使用 ITypeConverter 进行 AutoMapper 依赖注入

Jho*_*ena 5 dependency-injection typeconverter automapper .net-core asp.net-core

我正在尝试使用 Automapper 将所有日期时间从 UTC 转换为本地时间,但我需要将接口注入 ITypeConverter...运行应用程序时收到此错误:MissingMethodException:没有为此对象定义无参数构造函数。

我认为问题出在依赖注入代码上!

有人可以帮助我吗?

用户存储库:

public class UserRepository : IUserRepository
{
    private static readonly MapperConfiguration Config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<User, User>();

        cfg.CreateMap<DateTime?, DateTime?>().ConvertUsing<UtcToLocalConverter>();
    });

    public List<User> GetById(string[] ids)
    {
        var result = BuildQuery().Where(w => ids.Contains(w.UserName)).ToList();

        var mapper = Config.CreateMapper();

        return mapper.Map<List<User>>(result); // Throws error !!!
    }

    #region Helper

    private IQueryable<User> BuildQuery()
    {
        return Settings.EpedDb.User;
    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)

转换器

public class UtcToLocalConverter : ITypeConverter<DateTime?, DateTime?>
{
    public UtcToLocalConverter(IBaseSettings baseClass) // I tried to inject here!!!
    {
        Settings = baseClass;
    }

    private IBaseSettings Settings { get; }

    public DateTime? Convert(DateTime? source, DateTime? destination, ResolutionContext context)
    {
        if (source == null) return null;

        var tzi = TimeZoneInfo.FindSystemTimeZoneById(Settings.UserData.TimeZone);
        return TimeZoneInfo.ConvertTime(DateTime.SpecifyKind((DateTime)source, DateTimeKind.Utc), tzi);
    }
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*ini 3

您的预感是正确的:当您使用 时,您无法将任何参数注入到构造函数中CreateUsing<TTypeConverter>()。该类型必须具有无参数构造函数。

您可以将单个实例传递给CreateUsing():

var converter = new UtcToLocalConverter(mySettings);
cfg.CreateMap<DateTime?, DateTime?>().ConvertUsing(converter);
Run Code Online (Sandbox Code Playgroud)

但我怀疑这行不通,因为您正在使用依赖项注入来尝试在运行时处理用户的时区。

我认为解决您问题的真正解决方案是不在应用程序的这一层处理时区。.NETDateTime类在处理时区方面非常糟糕。

你应该:

  • 使用DateTimeOffset?而不是DateTime?
  • 始终以 UTC 格式存储日期(偏移量 0)
  • 不用担心应用程序代码中的时区转换
  • 在渲染或表示层,渲染用户本地时区的 UTC 日期

这是处理日期和时区的更简洁的方式。