5

私はEFとNinjectの両方に慣れていないので、これが意味をなさない場合は許してください:)

NinjectおよびNinject.Web.Common参照を持つMVC3アプリケーションがあります。リポジトリにDbContextを挿入しようとしています。私が見ているのは、最初のリクエストではすべてがうまく機能しますが、後続のリクエストは次のように返されるということです。

System.InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)

私のバインディング:

kernel.Bind<ISiteDataContext>().To<SiteDataContext>().InRequestScope();
kernel.Bind<IProductRepository>().To<ProductRepository>();
kernel.Bind<IProductService>().To<ProductService>();

私のサービスクラス:

public class ProductService : IProductService {
    [Inject]
    public IProductRepository repository {get; set;}

    ...
}

私のリポジトリクラス:

public class ProductRepository : IProductRepository {
    [Inject]
    public ISiteDataContext context {get; set;}

    ...
}

My SiteDataContextクラス:

public class SiteDataContext  : DbContext, ISiteDataContext 
{
    static SiteDataContext()
    {
        Database.SetInitializer<SiteDataContext >(null);
    }

    public DbSet<Product> Products{ get; set; }


    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
    }
}

私のコントローラー:

public class ProductController {
    [Inject]
    public IProductService productService {get; set;}

    ...
}

.InRequestScope()を削除すると、正常に機能しますが、オブジェクトがデータコンテキストの複数の個別のインスタンスで変更されるため、EntityFrameworkで問題が発生します。

4

3 に答える 3

6

リポジトリも InRequestScope になるように設定します。リクエストごとに破棄する必要があります。

また、MVC では、コンストラクター インジェクションを使用して、リポジトリをコントローラー インスタンスにもインジェクトする必要があります。

于 2012-06-22T03:47:32.647 に答える
5

当然のことながら、投稿した直後に何かが頭に浮かび、これを解決することができました.

問題は、ActionFilters の動作が MVC3 で変更され、ProductService が注入されたフィルターがあったという事実にあります。

フィルターがサービスを破棄し、最終的に DbContext を破棄したと思います。

私の場合、解決策は簡単でした。フィルター専用の 2 つ目の DbContext を作成しました。フィルターは、特定のリソースへの承認を確認するために選択したいくつかのテーブルを照会するだけなので、単一の要求で DbContext が提供する作業単位コンテキストは必要ありませんでした。新しい DbContext を使用する新しいサービスを作成しました。この場合、InTransientScope() で構成するだけで十分です。

于 2012-06-22T03:50:11.117 に答える