さまざまなタスクを並行して実行するある種のスケジューラを書いています。IoC コンテナーとして MEF を使用します。ObjectContext の静的インスタンスを共有するのは得策ではないことがわかっているため、スレッドごとにインスタンスを作成することにしました。私は次のように実装しました:
[Export(typeof(IDatabaseFactory))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class DatabaseFactory : IDatabaseFactory
{
[Import]
public IServiceResolver ServiceResolver { get; set; }
[ThreadStatic]
private static IEntityModel _dataContext;
public IEntityModel Get()
{
if (_dataContext == null)
{
Debug.WriteLine("*************************");
Debug.WriteLine(string.Format("Created Context Instance on Thread {0}", Thread.CurrentThread.ManagedThreadId));
Debug.WriteLine("*************************");
}
return _dataContext ?? (_dataContext = ServiceResolver.GetService<IEntityModel>());
}
public void Dispose()
{
Debug.WriteLine("^^^^^^^^Disposing Context^^^^^^^^");
if (_dataContext != null)
{
_dataContext.Dispose();
_dataContext = null;
}
}
}
_dataContext フィールドの ThreadStatic 属性に注目してください。このコードは次の出力で失敗します。
*************************
Created Context Instance on Thread 9
*************************
-- Running Main Thread on thread 9
-- Scheduling servicetask of type ActiveDirectorySynchronisationServiceTask on thread 14
-- Scheduling servicetask of type LogCleanerServiceTask on thread 15
-- Scheduling servicetask of type TranscriptParseServiceTask on thread 17
-- Scheduling servicetask of type MailServiceTask on thread 16
*************************
*************************
Created Context Instance on Thread 15
*************************
Created Context Instance on Thread 17
*************************
Created Context Instance on Thread 16
*************************
*************************
次のエラーメッセージが表示されます:
{"The transaction operation cannot be performed because there are pending requests working on this transaction."}
実際のエラーは常に同じであるとは限らないことに注意してください (「基になるプロバイダーがオープンに失敗した」など)、これはマルチスレッドの問題であると確信しています。しかし、問題がわかりませんか?
接続は ObjectContext のインスタンス間で共有されますか? EF4.0、SQL Server Express 2008 を使用しています