[英]In F#, how do I tell if an object is an Async<_>, and how can I cast it to an Async<_>?
我目前正在嘗試創建一個IHttpActionInvoker
,用於ASP.NET Web API,允許結果為Async<'T>
。 目前,我忽略了IHttpActionResult
的轉換,只關心HttpResponseMessage
和類型為'T
的值。 我目前有以下實現:
type AsyncApiActionInvoker() =
inherit Controllers.ApiControllerActionInvoker()
override x.InvokeActionAsync(actionContext, cancellationToken) =
if actionContext = null then
raise <| ArgumentNullException("actionContext")
let actionDescriptor = actionContext.ActionDescriptor
Contract.Assert(actionDescriptor <> null)
if actionDescriptor.ReturnType = typeof<Async<HttpResponseMessage>> then
let controllerContext = actionContext.ControllerContext
Contract.Assert(controllerContext <> null)
let task = async {
let! asyncResult = Async.AwaitTask <| actionDescriptor.ExecuteAsync(controllerContext, actionContext.ActionArguments, cancellationToken)
// For now, throw if the result is an IHttpActionResult.
if typeof<IHttpActionResult>.IsAssignableFrom(actionDescriptor.ReturnType) then
raise <| InvalidOperationException("IHttpResult is not supported when returning an Async")
let! result = asyncResult :?> Async<HttpResponseMessage>
return actionDescriptor.ResultConverter.Convert(controllerContext, result) }
Async.StartAsTask(task, cancellationToken = cancellationToken)
else base.InvokeActionAsync(actionContext, cancellationToken)
這僅適用於Async<HttpResponseMessage>
。 如果我嘗試轉換為Async<_>
,我會得到一個異常,說明我無法轉換為Async<obj>
。 我也無法正確檢測actionDescriptor.ReturnType
是否為Async<_>
。 這並不讓我感到驚訝,但我不確定如何解決這個問題。
作為選項(瀏覽器編譯的代碼,可能包含錯誤)
let (|Async|_|) (ty: Type) =
if ty.IsGenericType && ty.GetGenericTypeDefinition() = typedefof<Async<_>> then
Some (ty.GetGenericArguments().[0])
else
None
type AsyncApiActionInvoker() =
inherit Controllers.ApiControllerActionInvoker()
static let AsTaskMethod = typeof<AsyncApiActionInvoker>.GetMethod("AsTask")
static member AsTask<'T> (actionContext: Controllers.HttpActionContext, cancellationToken: CancellationToken) =
let action = async {
let task =
actionContext.ActionDescriptor.ExecuteAsync(
actionContext.ControllerContext,
actionContext.ActionArguments,
cancellationToken
)
let! result = Async.AwaitTask task
let! asyncResult = result :?> Async<'T>
return actionContext.ActionDescriptor.ResultConverter.Convert(actionContext.ControllerContext, box asyncResult)
}
Async.StartAsTask(action, cancellationToken = cancellationToken)
override x.InvokeActionAsync(actionContext, cancellationToken) =
if actionContext = null then
raise <| ArgumentNullException("actionContext")
match actionContext.ActionDescriptor.ReturnType with
| Async resultType ->
let specialized = AsTaskMethod.MakeGenericMethod(resultType)
downcast specialized.Invoke(null, [|actionContext, cancellationToken|])
| _ -> base.InvokeActionAsync(actionContext, cancellationToken)
在StackOverflow外部提供了一些有用的提示之后,我想出了以下可行的解決方案。 我並不為此感到興奮,但它確實起到了作用。 我很感激任何提示或指示:
type AsyncApiActionInvoker() =
inherit Controllers.ApiControllerActionInvoker()
static member internal GetResultConverter(instanceType: Type, actionDescriptor: HttpActionDescriptor) : IActionResultConverter =
if instanceType <> null && instanceType.IsGenericParameter then
raise <| InvalidOperationException()
if instanceType = null || typeof<HttpResponseMessage>.IsAssignableFrom instanceType then
actionDescriptor.ResultConverter
else
let valueConverterType = typedefof<ValueResultConverter<_>>.MakeGenericType instanceType
let newInstanceExpression = Expression.New valueConverterType
let ctor = Expression.Lambda<Func<IActionResultConverter>>(newInstanceExpression).Compile()
ctor.Invoke()
static member internal StartAsTask<'T>(task, resultConverter: IActionResultConverter, controllerContext, cancellationToken) =
let computation = async {
let! comp = Async.AwaitTask task
let! (value: 'T) = unbox comp
return resultConverter.Convert(controllerContext, value) }
Async.StartAsTask(computation, cancellationToken = cancellationToken)
override this.InvokeActionAsync(actionContext, cancellationToken) =
if actionContext = null then
raise <| ArgumentNullException("actionContext")
let actionDescriptor = actionContext.ActionDescriptor
Contract.Assert(actionDescriptor <> null)
let returnType = actionDescriptor.ReturnType
// For now, throw if the result is an IHttpActionResult.
if typeof<IHttpActionResult>.IsAssignableFrom(returnType) then
raise <| InvalidOperationException("IHttpResult is not supported when returning an Async")
if returnType.IsGenericType && returnType.GetGenericTypeDefinition() = typedefof<Async<_>> then
let controllerContext = actionContext.ControllerContext
Contract.Assert(controllerContext <> null)
let computation = actionDescriptor.ExecuteAsync(controllerContext, actionContext.ActionArguments, cancellationToken)
let innerReturnType = returnType.GetGenericArguments().[0]
let converter = AsyncApiActionInvoker.GetResultConverter(innerReturnType, actionDescriptor)
this.GetType()
.GetMethod("StartAsTask", BindingFlags.NonPublic ||| BindingFlags.Static)
.MakeGenericMethod(innerReturnType)
.Invoke(null, [| computation; converter; controllerContext; cancellationToken |])
|> unbox
else base.InvokeActionAsync(actionContext, cancellationToken)
我希望這有助於其他人!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.