[英]static class configuration for service fabric actors
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 構造函數()或如下所示的主要方法)中聲明上述靜態方法:
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;
}
}
我通常不想回答我自己的問題,但這是我目前所發現的。
首先,如果我希望解決問題的實際解決方案與標題本身更相關,也許我需要更改此問題的標題。 但是,由於這篇文章已回答了標題問題,因此我將保持原樣。
簡而言之,靜態類配置可以在我上面提到的所有地方完成,例如 Actor 構造函數、OnActivateAsync() 等,因為靜態類仍然在 AppDomain 內的不同線程之間共享(Actor 都是單個獨立線程) (並且演員在 AppDomain 中運行。如果我錯了,請糾正我。)
導致上述問題的真正原因是因為使用 Dapper 的映射定義被聲明為動態的; 如下圖:
return sqlConnection.Query<dynamic>(some_sql_script, new { objInstance }).FirstOrDefault();
一旦將預期的返回類型 T 更改為包含 typeHandler 類型的強類型,Dapper 就會正確調用 typeHandler:
return sqlConnection.Query<StrongType>(some_sql_script, new { objInstance }).FirstOrDefault();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.