0

Func を渡す Web API ベース コントローラーにジェネリック メソッドがあります。

説明するには、次のコードを参照してください

public class StuffController : BaseController
{
    // method #1
    [HttpGet]
    public async Task<HttpResponseMessage> GetWidget(int id)
    {
        return await ProcessRestCall(async rc => await rc.GetWidgetAsync(id));
    }

    // method #2
    [HttpGet]
    public async Task<HttpResponseMessage> GetWidget(int year, int periodId, int modelId, int sequenceId)
    {
        return await ProcessRestCall(async rc => await rc.GetWidgetAsync(year, periodId, modelId, sequenceId));
    }

    // method #3
    [HttpGet]
    public async Task<HttpResponseMessage> DecodeWidget(string sid)
    {
        return await ProcessRestCall(async rc => await rc.GetIdsAsync(sid));
    }
}


public class BaseController : ApiController
{
    [NonAction]
    protected async Task<HttpResponseMessage> ProcessRestCall<T>(Func<RestClient, Task<T>> restClientCallback) where T : class
    {
        // stuff happens...

        // TODO: here I'd like to capture parameters (and their types) of the await methods passed to restClientCallback via lambdas...
        // for example, in case of method #2 I would  get params object [] containing year, periodId, modelId, sequenceId
        T result = await restClientCallback(restClient);

        // more stuff...
        var response = Request.CreateResponse(HttpStatusCode.OK, result);        
        return response;
    }
}

更新 (「なぜこれを行うのですか?」)

上記のProcessRestCall方法は多くのことを行いますが、主にログイン、データの取得、ログアウトを行います...ログイン後にデータを返し、パフォーマンスを向上させるために使用したいシンプルで小さなメモリキャッシュがあります。「残りのクライアント」とその動作を制御することはできません。私の WidgetCache は System.Runtime.Caching.MemoryCache をラップし、"typeof(T)-id(-id)*" を文字列キャッシュ キーとして使用します。キャッシュキーを生成するには、(私が持っている) 結果のタイプと、1 つ以上の関連 ID (labbda コールバック内でパラメーターとして渡される) が必要です。

可能な回避策(おそらくさらにクリーンなアプローチ)

このデータをキャプチャして、パラメータとして送信できますProcessRestCall

public async Task<HttpResponseMessage> GetWidget(int id)
{
    var cacheKey = Cache.GenerateKeyFor(typeof(Widget), id);
    return await ProcessRestCall(async rc => await rc.GetWidgetAsync(id), cacheKey);
}
4

0 に答える 0