MediatR和SimpleInjector

时间:2016-07-27 14:11:20

标签: c# entity-framework simple-injector mediator mediatr

我一直在WinForms应用程序中使用MediatR库试验中介模式和CQRS,该应用程序使用实体框架进行数据访问。该应用程序用于批生产工厂,允许用户查看活动和已完成批次的列表,并在必要时更新批次信息。每批都有大量与之相关的信息,例如质量和过程测量。根据这些文章,读取和写入数据被组织到查询和命令中:

Meanwhile... on the query side of my architecture

CQRS with MediatR and AutoMapper

以下是查询和查询处理程序的简单示例。使用SimpleInjector将DataContext注入到查询处理程序中。

public class GetAllBatchesQuery: IRequest<IEnumerable<Batch>> { }

public class GetAllBatchesQueryHandler :
    IRequestHandler<GetAllBatchesQuery, IEnumerable<Batch>>
{
    private readonly DataContext _context;

    public GetAllBatchesQueryHandler(DataContext context)
    {
        _context= context;
    }

    public IEnumerable<Batch> Handle(GetAllBatchesQueryrequest)
    {
        return _db.Batches.ToList();
    }
}

这将从演示者调用如下:

var batches = mediator.Send(new GetAllBatchesQuery());

我遇到的问题是DbContext的生命周期。理想情况下,我希望每个隔离事务使用一个实例,在这种情况下,它包括以下内容:

  • 从数据库中检索批次列表
  • 检索批次的质量指标列表(这些指标存储在不同的数据库中并通过存储过程访问)
  • 更新批次,可能包括更新数据库中的多个实体

这会让我走向DbContext的范围或短暂的生活方式。但是,当使用瞬态生活方式时,SimpleInjector会引发以下错误,在注册类型时会引发以下错误:

container.Register<DataContext>();
  

SimpleInjector.dll中出现未处理的“SimpleInjector.DiagnosticVerificationException”类型异常

     

其他信息:配置无效。报告了以下诊断警告:

     

- [Disposable Transient Component] DataContext注册为transient,但实现了IDisposable。

在SimpleInjector网站上研究此问题会显示以下note

  

警告:容器不会跟踪瞬态实例。这意味着Simple Injector不会处置瞬态实例。

这使我走上了为DataContext使用Lifetime Scope生活方式的道路。为此,我为我的查询创建了一个新的装饰器类,并将其注册如下:

public class LifetimeScopeDecorator<TRequest, TResponse> :
    IRequestHandler<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    private readonly IRequestHandler<TRequest, TResponse> _decorated;
    private readonly Container _container;

    public LifetimeScopeDecorator(
        IRequestHandler<TRequest, TResponse> decorated,
        Container container)
    {
        _decorated = decorated;
        _container = container;
    }

    public TResponse Handle(TRequest message)
    {
        using (_container.BeginLifetimeScope())
        {
            var result = _decorated.Handle(message);
            return result;
        }
    }
}

...

container.RegisterDecorator(
    typeof(IRequestHandler<,>),
    typeof(ExecutionContextScopeDecorator<,>));

但是,进行此更改会导致另一个异常,这次会抛出以下行:

var batches = mediator.Send(new GetAllBatchesQuery());
  

MediatR.dll中出现未处理的“System.InvalidOperationException”类型异常

     

其他信息:找不到类型为MediatorTest.GetAllBatchesQuery的请求处理程序。

     

未正确配置容器或服务定位器或未在容器中注册处理程序。

调试并查看MediatR代码后,似乎在调用mediator.Send(...)方法时,通过调用GetAllBatchesQueryHandler创建container.GetInstance()类的新实例。但是,由于DataContext此时不在执行范围内,因此可能无法正确初始化,从而导致异常。

我相信我了解问题的根本原因,但对如何有效解决问题感到茫然。为了更好地说明这个问题,我开发了以下最小的例子。任何实现IDisposable的类都会导致与DataContext相同的问题。

using System;
using System.Collections.Generic;
using System.Reflection;
using MediatR;
using SimpleInjector;
using SimpleInjector.Extensions.LifetimeScoping;

namespace MediatorTest
{
    public class GetRandomQuery : IRequest<int>
    {
        public int Min { get; set; }
        public int Max { get; set; }
    }

    public class GetRandomQueryHandler : IRequestHandler<GetRandomQuery, int>
    {
        private readonly RandomNumberGenerator _r;

        public GetRandomQueryHandler(RandomNumberGenerator r)
        {
            _r = r;
        }

        public int Handle(GetRandomQuery request)
        {
            return _r.Next(request.Min, request.Max);
        }
    }

    public class RandomNumberGenerator : IDisposable
    {
        private Random _random = new Random();

        public RandomNumberGenerator() { }

        public void Dispose() { }

        public int Next(int min, int max)
        {
            var result = _random.Next(min, max);
            return result;
        }
    }

    public class LifetimeScopeDecorator<TRequest, TResponse> :
        IRequestHandler<TRequest, TResponse>
        where TRequest : IRequest<TResponse>
    {
        private readonly IRequestHandler<TRequest, TResponse> _decorated;
        private readonly Container _container;

        public LifetimeScopeDecorator(
            IRequestHandler<TRequest, TResponse> decorated,
            Container container)
        {
            _decorated = decorated;
            _container = container;
        }

        public TResponse Handle(TRequest message)
        {
            using (_container.BeginLifetimeScope())
            {
                var result = _decorated.Handle(message);
                return result;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var assemblies = GetAssemblies();

            var container = new Container();
            container.Options.DefaultScopedLifestyle = new LifetimeScopeLifestyle();
            container.RegisterSingleton<IMediator, Mediator>();
            container.Register<RandomNumberGenerator>(Lifestyle.Scoped);
            container.Register(typeof(IRequestHandler<,>), assemblies);
            container.RegisterSingleton(new SingleInstanceFactory(container.GetInstance));
            container.RegisterSingleton(new MultiInstanceFactory(container.GetAllInstances));
            container.RegisterDecorator(
                typeof(IRequestHandler<,>),
                typeof(LifetimeScopeDecorator<,>));

            container.Verify();

            var mediator = container.GetInstance<IMediator>();

            var value = mediator.Send(new GetRandomQuery() { Min = 1, Max = 100 });

            Console.WriteLine("Value = " + value);

            Console.ReadKey();
        }

        private static IEnumerable<Assembly> GetAssemblies()
        {
            yield return typeof(IMediator).GetTypeInfo().Assembly;
            yield return typeof(GetRandomQuery).GetTypeInfo().Assembly;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

问题是你的decoratee(具有DbContext依赖关系)是在创建装饰器时创建的,并且那时没有活动范围(因为你在以后的某个时间点创建它) 。你应该使用decoratee工厂描述here。换句话说,您的LifetimeScopeDecorator应按以下方式实施:

public class LifetimeScopeDecorator<TRequest, TResponse> :
    IRequestHandler<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    private readonly Func<IRequestHandler<TRequest, TResponse>> _decorateeFactory;
    private readonly Container _container;

    public LifetimeScopeDecorator(
        Func<IRequestHandler<TRequest, TResponse>> decorateeFactory,
        Container container)
    {
        _decorateeFactory = decorateeFactory;
        _container = container;
    }

    public TResponse Handle(TRequest message)
    {
        using (_container.BeginLifetimeScope())
        {
            var result = _decorateeFactory.Invoke().Handle(message);
            return result;
        }
    }
}

与原始实现的不同之处在于注入了Func<IRequestHandler<TRequest, TResponse>>而不是IRequestHandler<TRequest, TResponse>。这允许Simple Injector在创建范围后推迟创建。