Service Fabric Actor 用于访问数据库,所有方法都假设使用 Dapper 作为 ORM 工具。
我发现作为解决当前问题的最佳方法的一件事是在 Dapper 中使用称为 SqlMapper 的东西。这样,您可以定义处理某些数据类型的一般行为,例如:
SqlMapper.AddTypeHandler(new DateTimeHandler());
public class DateTimeHandler : SqlMapper.TypeHandler<DateTime>
{
public override void SetValue(IDbDataParameter parameter, DateTime dateTime)
{
parameter.Value = dateTime.ValidateDateTime();
}
public override DateTime Parse(object value)
{
return ((DateTime)value).ValidateDateTime();
}
}
当您使用 DateTimeHandler 等自定义处理程序声明上述静态方法 (AddTypeHandler) 时,使用 Dapper 框架完成的映射将确保任何 dateTime 类型正确通过上述处理程序。
我希望看到这种情况发生在每个 Actor 通过 Dapper 与数据库通信时。我还没有看到它在尝试使用几个不同的地方(例如 Actor constructor() 或 main 方法,如下所示)声明上述静态方法:
private static void Main()
{
try
{
// This line registers an Actor Service to host your actor class with the Service Fabric runtime.
// The contents of your ServiceManifest.xml and ApplicationManifest.xml files
// are automatically populated when you build this project.
// For more information, see https://aka.ms/servicefabricactorsplatform
ActorRuntime.RegisterActorAsync<SqlRepositoryActor>(
(context, actorType) => new ActorService(context, actorType)).GetAwaiter().GetResult();
// This doesn't seem like a right place as I don't see the handler being called when Actor uses dapper mapping methods.
SqlMapper.AddTypeHandler(new DateTimeHandler());
Thread.Sleep(Timeout.Infinite);
}
catch (Exception e)
{
ActorEventSource.Current.ActorHostInitializationFailed(e.ToString());
throw;
}
}