1

私は3層MVCアプリケーションに取り組んでいます。データレイヤーには、EF4コードファーストのDbContextが含まれています。

public class MyDataContext : DbContext
{
    // DbSet<>s...
}

DIのインターフェースと実装もあります。

public interface IContextFactory
{
    MyDataContext GetContext();
}

public class ContextFactory : IContextFactory
{
    readonly MyDataContext context;
    public ContextFactory(MyDataContext context)
    {
        this.context = context;
    }

    public MyDataContext GetContext()
    {
        return this.context;
    }
}

そしてリポジトリパターン:

public interface IRepository<T>
{
    T Create();
    void Insert(T entity);
    void Delete(T entity);
    ...
    void Save();
}

public class Repository<TEntity> : IRepository<TEntity>
  where TEntity: class, new()
{
    public Repository(IContextFactory factory)
    {
        this.context = factory.GetContext();
        this.set = factory.Set<TEntity>();
    }
    ...
}

上位層はIRepository<>、城のウィンザーを注入することによってエンティティにアクセスします。カスタムプロバイダー/モジュールは、必要に応じて明示的に.Resolve<>()それらを作成します。

データレイヤーは城に登録されていますIWindsorInstaller

container.Register(
    Component.For<MyDataContext>()
    .DependsOn(new Hashtable() { {"connectionStringName", "DefaultConnection"} })
    .LifestylePerWebRequest());

container.Register(
    Component.For<IContextFactory>()
    .ImplementedBy<ContextFactory>()
    .LifestylePerWebRequest());

container.Register(
     Component.For(typeof(IRepository<>))
    .ImplementedBy(typeof(Repository<>))
    .LifestylePerWebRequest());

私は何が間違っているのかわかりません-私のテストはデータコンテキストをカバーしていません-しかしデバッグモードでは、私のデータコンテキストのコンストラクターはWebリクエストごとにほぼ12回呼び出されます。

編集:理由は説明されておらずRepositoryMyDataContextWebリクエストのスコープが設定されていませんが、コンストラクター内のブレークポイントは、構築されたものと同じ呼び出しスタックを数十回明らかにしていますMembershipProvider.GetUser -> new Repository(IContextFactory)。明示的な呼び出しはありませんGetUser-FormsAuthenticationがGetUserを何度も呼び出す原因は、いったい何でしょうか?

4

1 に答える 1

2

Global.asax.cs ファイルに次のようなものを追加します。

    protected void Application_BeginRequest(object sender, EventArgs args)
    {
        System.Diagnostics.Debug.WriteLine(this.Request.RequestType + " " + this.Request.RawUrl);
    }

デバッガーに接続して、「リクエスト」ごとに 1 つのリクエストしかないことを確認します。並列に ajax リクエストを実行している可能性があります。または、コンテンツ要素 (js ファイル、画像) が保護されていて、それらの get が C# コードを実行している可能性があります。

于 2012-07-25T07:13:04.967 に答える