SimpleInjectorIoCライブラリとして使用しています。DbContextWebリクエストに従って登録しましたが、正常に機能します。しかし、バックグラウンドスレッドで実行するタスクが1つあります。DbContextそのため、インスタンスの作成に問題があります。例えば
Service1のインスタンスがありますDbContextService2のインスタンスがありますDbContextService1Service2バックグラウンドスレッドから実行します。Service1エンティティをフェッチしてに渡しますService2Service2そのエンティティを使用しますが、エンティティはから切り離されています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。