我需要将NodaTime LocalDateTime存储在Akavache缓存中。
我创建了一个简单的应用程序,它接受以下类并将其存储/从Akavache缓存中检索:
public class TestModel
{
public string Name { get; set; }
public LocalDateTime StartDateTimeLocal {get; set;}
public DateTime StartDateTimeUtc {get;set;}
}当它存储在缓存中并从缓存中检索时,还没有填充StartDateTimeLocal属性。
看来Akavache不知道如何序列化/反序列化LocalDateTime。
是否可以向Akavache注册类型或为未知类型提供自定义序列化?
控制台应用程序来演示它:
using Akavache;
using NodaTime;
using System;
using System.Reactive.Linq;
namespace AkavacheNodaTimeCore
{
class Program
{
static TestModel BeforeModel;
static TestModel AfterModel;
static void Main(string[] args)
{
// Note that we're using Akavache 6.0.27, to match the version we're using in our live system.
BlobCache.ApplicationName = "AkavacheNodaTimeCore";
BlobCache.EnsureInitialized();
BeforeModel = new TestModel()
{
StartLocalDateTime = LocalDateTime.FromDateTime(DateTime.Now),
StartDateTime = DateTime.UtcNow,
};
Console.WriteLine($"Before:LocalDateTime='{BeforeModel.StartLocalDateTime}' DateTime='{BeforeModel.StartDateTime}'");
CycleTheModels();
Console.WriteLine($"After: LocalDateTime='{AfterModel.StartLocalDateTime}' DateTime='{AfterModel.StartDateTime}'");
Console.WriteLine("Note that Akavache retrieves DateTimes as DateTimeKind.Local, so DateTime before and after above will differ.");
Console.WriteLine("Press any key to continue.");
var y = Console.ReadKey();
}
/// <summary>
/// Puts a model into Akavache and retrieves a new one so we can compare.
/// </summary>
static async void CycleTheModels()
{
await BlobCache.InMemory.Invalidate("model");
await BlobCache.InMemory.InsertObject("model", BeforeModel);
AfterModel = await BlobCache.InMemory.GetObject<TestModel>("model");
}
}
}TestModel类:
using NodaTime;
using System;
namespace AkavacheNodaTimeCore
{
public class TestModel
{
public string Name { get; set; }
public LocalDateTime StartLocalDateTime { get; set; }
public DateTime StartDateTime {get;set;}
}
}我在控制台应用程序中添加了一个带有上述内容的Git回购,这说明了这个问题。
发布于 2019-06-13 09:24:55
您需要配置Akavache与JsonSerializerSettings一起使用的Json.NET,您需要一个对NodaTime.Serialization.JsonNet的引用,此时您可以创建一个序列化程序设置实例,为Noda配置它,然后在Splat中添加它作为一个依赖项( Akavache使用它)。我以前没有使用过Splat,所以这可能不是正确的方法,但它适用于您的示例:
using Newtonsoft.Json;
using NodaTime.Serialization.JsonNet;
using Splat;
...
// This should be before any of your other code.
var settings = new JsonSerializerSettings();
settings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
Locator.CurrentMutable.RegisterConstant(settings, typeof(JsonSerializerSettings));可能值得在Akavache回购中提交更多的文档,以便定制序列化设置--上面的工作,但只是猜测和一点源代码调查。
https://stackoverflow.com/questions/56562375
复制相似问题