SimpleInjector
IoCライブラリとして使用しています。DbContext
Webリクエストに従って登録しましたが、正常に機能します。しかし、バックグラウンドスレッドで実行するタスクが1つあります。DbContext
そのため、インスタンスの作成に問題があります。例えば
Service1
のインスタンスがありますDbContext
Service2
のインスタンスがありますDbContext
Service1
Service2
バックグラウンドスレッドから実行します。Service1
エンティティをフェッチしてに渡しますService2
Service2
そのエンティティを使用しますが、エンティティはから切り離されていますDbContext
実際に問題はここにあります:Service1.DbContext
との違いですService2.DbContext
。
ASP.NET MVCの別のスレッドでタスクを実行すると、呼び出しごとSimpleInjector
にの新しいインスタンスが作成されるようです。DbContext
一部のIoCライブラリ(たとえばStructureMap
)には、スレッドごと、Webリクエストごとのライフスタイルが混在していますが、そうでSimpleInjector
はないようです。私は正しいですか?
この問題を解決するためのアイデアはありSimpleInjector
ますか?前もって感謝します。
編集:
私のサービスはここにあります:
class Service1 : IService1 {
public Service1(MyDbContext context) { }
}
class Service2 : IService2 {
public Service2(MyDbContext context, IService1 service1) { }
}
class SyncServiceUsage {
public SyncServiceUsage(Service2 service2) {
// use Service2 (and Service1 and DbContext) from HttpContext.Current
}
}
class AsyncServiceUsage {
public AsyncServiceUsage(Service2 service2) {
// use Service2 (and Service1 and DbContext) from background thread
}
}
public class AsyncCommandHandlerDecorator<TCommand>
: ICommandHandler<TCommand> where TCommand : ICommand {
private readonly Func<ICommandHandler<TCommand>> _factory;
public AsyncCommandHandlerDecorator(Func<ICommandHandler<TCommand>> factory) {
_factory = factory;
}
public void Handle(TCommand command) {
ThreadPool.QueueUserWorkItem(_ => {
// Create new handler in this thread.
var handler = _factory();
handler.Handle(command);
});
}
}
void InitializeSimpleInjector() {
register AsyncCommandHandlerDecorator for services (commands actually) that starts with "Async"
}
Service2
私は時々ユーザーになりますAsyncService2
。