我正在SimpleInjector用作我的 IoC 库。我DbContext根据网络请求注册,它工作正常。但是有一项任务是我在后台线程中运行的。所以,我在创建DbContext实例时遇到了问题。例如
Service1有一个实例DbContextService2有一个实例DbContextService1并Service2从后台线程运行。Service1获取一个实体并将其传递给Service2Service2使用该实体,但实体与DbContext
实际上问题就在这里:Service1.DbContext与Service2.DbContext.
似乎当我在 ASP.NET MVC 的单独线程中运行任务时,会为每个调用SimpleInjector创建一个新实例。DbContext虽然一些 IoC 库(例如StructureMap)对 per-thread-per-webrequest 有一种混合的生活方式,但似乎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其他时间用户。