在 F# 中,我如何确定一个对象是否是 Async<_>,并如何将其转换为 Async<_>?

3

我目前正在尝试创建一个可用于ASP.NET Web API的,它将允许结果为异步>。目前,我忽略了转换,只关心和类型的值。我目前有以下实现:

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<_>。 这并不让我感到惊讶,但我不知道该如何解决问题。

2个回答

2
作为一种选择(由浏览器编译的代码,可能包含错误)。
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)

1
这提供了一个更好的解决方案。谢谢!更新后的代码片段可以在这里找到:http://fssnip.net/pZ - panesofglass

0

在从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)

希望这能帮助到其他人!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接