相关疑难解决方法(0)

使用简单注入器的每线程和每Web请求的混合生活方式

SimpleInjector用作我的IoC库.我DbContext根据网络请求注册,它工作正常.但是我有一个任务是在后台线程中运行它.所以,我有一个问题来创建DbContext实例.例如

  1. Service1 有一个实例 DbContext
  2. Service2 有一个实例 DbContext
  3. Service1Service2从后台线程运行.
  4. Service1 获取实体并将其传递给 Service2
  5. Service2 使用该实体,但实体与之分离 DbContext

实际上问题出在这里:Service1.DbContext与众不同Service2.DbContext.

当我在ASP.NET MVC中的一个单独的线程中运行任务时,似乎为每个调用SimpleInjector创建一个新实例DbContext.虽然一些IoC库(例如StructureMap)对于每个web-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 …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection inversion-of-control simple-injector

14
推荐指数
1
解决办法
5780
查看次数

如何配置Simple Injector以在ASP.NET MVC中运行后台线程

我正在使用Simple Injector来管理我注入的依赖项的生命周期(在这种情况下UnitOfWork),我很高兴有一个单独的装饰器而不是我的服务或命令处理程序,在编写业务逻辑时保存和处理使代码更容易图层(我遵循本博文中概述的架构).

通过在构造根容器的构造过程中使用Simple Injector MVC NuGet包和以下代码,上面的工作完美(并且非常容易),如果图中存在多个依赖项,则相同实例将全部注入 - 完美的实体框架模型上下文.

private static void InitializeContainer(Container container)
{
    container.RegisterPerWebRequest<IUnitOfWork, UnitOfWork>();
    // register all other interfaces with:
    // container.Register<Interface, Implementation>();
}
Run Code Online (Sandbox Code Playgroud)

我现在需要运行一些后台线程并从Simple Injector 文档中了解可以代理命令的线程,如下所示:

public sealed class TransactionCommandHandlerDecorator<TCommand>
    : ICommandHandler<TCommand>
{
    private readonly ICommandHandler<TCommand> handlerToCall;
    private readonly IUnitOfWork unitOfWork;

    public TransactionCommandHandlerDecorator(
        IUnitOfWork unitOfWork, 
        ICommandHandler<TCommand> decorated)
    {
        this.handlerToCall = decorated;
        this.unitOfWork = unitOfWork;
    }

    public void Handle(TCommand command)
    {
         this.handlerToCall.Handle(command);
         unitOfWork.Save();
    }
}
Run Code Online (Sandbox Code Playgroud)

ThreadedCommandHandlerProxy:

public class ThreadedCommandHandlerProxy<TCommand>
    : ICommandHandler<TCommand> …
Run Code Online (Sandbox Code Playgroud)

.net c# dependency-injection asp.net-mvc-3 simple-injector

8
推荐指数
2
解决办法
4419
查看次数