リクエストとレスポンスのフィルターを使用してアンビエント トランザクションをセットアップしました (実際には、私の場合は NHibernate セッションですが、考え方は似ています)。これは、AppHost のメソッドのRequestFilters
andコレクションに追加することで実現しました。ResponseFilters
Configure
また、成功した場合にトランザクションをコミットすることと、エラーが発生した場合にトランザクションをロールバック/クリアすることを区別する必要がありました。
// normally: commit the transaction
ResponseFilters.Add((req, res, dto) => DbConnectionUtility.CleanupTransactionsAndConnections(req.RawUrl));
// rollback if unhandled exception in a service method
ServiceExceptionHandler = (request, exception) =>
{
DbConnectionUtility.ClearSessions();
// run the default code that sends a nicely serialized error response
return DtoUtils.HandleException(this, request, exception);
};
// rollback if unhandled exception outside of service (e.g. in a filter)
var defaultExceptionHandler = ExceptionHandler;
ExceptionHandler = (httpReq, httpRes, operationName, ex) =>
{
DbConnectionUtility.ClearSessions();
// run the default code that sends a nicely serialized error response
defaultExceptionHandler(httpReq, httpRes, operationName, ex);
};