0

多くの場合、ASP.NET アプリケーションの任意の部分から、複数の要求にわたって同じ情報にアクセスする必要があります。以下の例を使用して、現在のリクエストの URL を取得しようとしています (必要なプロパティをよく忘れてしまいます)。ASP.NET が HttpContext を処理する方法に似たアプローチを考え出そうとしています。これまでのところ、私は次のことを思いつきました:

public interface ICustomContext {
    HttpContextBase Http { get; }
    string Url { get; }
}

public class CustomContext : ICustomContext {
    private readonly HttpContextBase _httpContext;

    public CustomContext(HttpContextBase httpContext) {
        _httpContext = httpContext;
    }

    public HttpContextBase Http {
        get { return _httpContext; }
    }

    public string Url {
        get { return Http.Request.Url.AbsoluteUri; }
    }
}

public class MyContext {
    private static ICustomContext _instance = new CustomContext(new HttpContextWrapper(HttpContext.Current));

    public static ICustomContext Current {
        get { return _instance; }
    }
}

これにより、後で独自のコンテキストの上に追加のプロパティを追加できます。私は簡単に言うことができればいいのにと思いました:

MyContext.Current.Url;

ただし、最初に呼び出されたときは常にページの URL を返します。これはある種のスレッドの問題だと思いますが、解決方法がわかりません。

助けていただければ幸いです。ああ、理想的には、クリーンで簡単にテストできるソリューションが欲しいことに注意してください。

ありがとう

4

2 に答える 2

0

手がかりは静的フィールドと並んでいると思います

private static ICustomContext _instance

に変更してみてください

public static ICustomContext Current {
        get { return new CustomContext(HttpContext.Current); }
    }
于 2012-08-08T15:10:59.460 に答える
0

これを処理する良い方法を見つけました。私の最初の考えは、インスタンスを HttpContext.Current.Items コレクションに格納することでした (これはリクエストごとに存在するため)。次に、Microsoft UnityをIocとして使用していて、オブジェクトをHttpContext.Current.Itemsコレクションに格納する独自のLifetimeManagerを定義したので、次のように言ってタイプを登録できることに気付きました。

container.RegisterType<HttpContextBase>(new InjectionFactory(c => {
    return new HttpContextWrapper(HttpContext.Current);
}));
container.RegisterType<ICustomContext, CustomContext>(new PerRequestLifetimeManager<ICustomContext>());

これで、静的プロパティを次のように定義できます。

public static ICustomContext Current {
    get { return DependencyResolver.Current.GetService<ICustomContext>(); }
}
于 2012-08-08T18:31:38.993 に答える