WithParameter メソッドを使用する場合、パラメータ インスタンスは、解決されたすべてのオブジェクトで同じになります。したがって、.WithParameter("context", new PcpContext())
解決された IRepository のインスタンスに対して、PcpContext クラスの同じインスタンスを効果的に使用しています。
現在のコードでは、IRepository インスタンスが破棄されると、その PcpContext インスタンスも破棄されます。その後、IRepository を解決しようとすると、破棄された PcpContext インスタンスが返されます。リクエストの最後に破棄される各 Http リクエストで、EF DbContext の新しいインスタンスを受け取る方法が必要です。
IRepository の解決が必要になるたびにコード ブロックが実行されるように、IRepository のコード ブロックを登録することもできます。
_builder.Register<IRepository>(c => new EfRepository(new PcpContext()))
より良いオプションは、新しい抽象化を作成し、クラスではなく新しい IDatabaseContext 抽象化に依存するようにIDatabaseContext
更新することです(これはすでに当てはまる場合があります:))。EfRepository
PcpContext
IDatabaseContext の実装クラスは、EF DbContext から継承し、おそらく接続文字列をパラメーターとして受け取る必要がある PcpContext クラスになります。
public class EfRepository : IRepository
{
private readonly IDatabaseContext _context;
public EfRepository(IDatabaseContext context)
{
_context = context;
}
...methods for add, delete, update entities
//There is no longer need for this to be disposable.
//The disaposable object is the database context, and Autofac will take care of it
//public void Dispose()
}
public interface IDatabaseContext : IDisposable
{
... declare methods for add, delete, update entities
}
public class PcpContext: DbContext, IDatabaseContext
{
public EntityFrameworkContext(string connectionString)
: base(connectionString)
{
}
...methods exposing EF for add, delete, update entities
//No need to implement IDisposable as we inherit from DbContext
//that already implements it and we don´t introduce new resources that should be disposed of
}
これは、IoC コンテナーを使用し、ライフタイム管理の負担をそれらに任せるというアイデアで改善されます。これで、Repository クラスを使い捨てにする必要も、その IDatabaseContext 依存関係を管理および破棄する必要もなくなりました。コンテキスト インスタンスを追跡し、必要に応じて破棄するのは Autofac です。
同じ理由で、データベース コンテキストの依存関係で InstancePerLifetimeScope を使用することをお勧めします。これは、同じ EF コンテキストが同じ Http 要求のすべてのリポジトリ インスタンスで共有され、要求の最後に破棄されることを意味します。
_builder.RegisterType<EfRepository>()
.As<IRepository>();
_builder.RegisterType<PcpContext>()
.As<IDatabaseContext>()
.WithParameter("connectionString", "NameOfConnStringInWebConfig")
.InstancePerLifetimeScope();