MediatR 和 SimpleInjector 的依赖范围问题
Dependency Scope Issues with MediatR and SimpleInjector
我一直在使用 Entity Framework 进行数据访问的 WinForms 应用程序中使用 MediatR 库来试验中介模式和 CQRS。该应用程序用于批次制造工厂,允许用户查看活动批次和已完成批次的列表,并在必要时更新批次信息。每个批次都有大量与之相关的信息,例如质量和过程测量。根据这些文章,读写数据被组织成查询和命令:
Meanwhile... on the query side of my architecture
CQRS with MediatR and AutoMapper
这是查询和查询处理程序的一个简单示例。 DataContext
使用 SimpleInjector 注入查询处理程序。
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 的范围内或短暂的生活方式。但是,当使用 transient 生活方式时,SimpleInjector 会引发以下错误,该错误是在注册类型时抛出的,如下所示:
container.Register<DataContext>();
An unhandled exception of type 'SimpleInjector.DiagnosticVerificationException' occurred in SimpleInjector.dll
Additional information: The configuration is invalid. The following diagnostic warnings were reported:
-[Disposable Transient Component] DataContext is registered as transient, but implements IDisposable.
在 SimpleInjector 网站上研究这个问题揭示了以下内容 note:
Warning: Transient instances are not tracked by the container. This means that Simple Injector will not dispose transient instances.
这让我走上了为 DataContext 使用 Lifetime Scope 生活方式的道路。为此,我为我的查询创建了一个新的装饰器 class 并将其注册如下:
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());
An unhandled exception of type 'System.InvalidOperationException' occurred in MediatR.dll
Additional information: Handler was not found for request of type MediatorTest.GetAllBatchesQuery.
Container or service locator not configured properly or handlers not registered with your container.
调试并查看 MediatR 代码后,似乎在调用 mediator.Send(...)
方法时,通过调用 [=19] 创建了 GetAllBatchesQueryHandler
class 的新实例=].但是,由于此时DataContext
不在执行范围内,可能没有正确初始化,导致异常。
我相信我了解问题的根本原因,但不知道如何有效地解决它。为了帮助更好地说明这个问题,我开发了以下最小示例。任何实现 IDisposable
的 class 都会导致与 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;
}
}
}
问题是您的装饰对象(及其 DbContext
依赖项)是在创建装饰器时创建的,并且那时没有活动范围(因为您稍后在时间)。您应该使用 here 中描述的 decoratee 工厂。换句话说,你的 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 在创建范围后推迟创建。
我一直在使用 Entity Framework 进行数据访问的 WinForms 应用程序中使用 MediatR 库来试验中介模式和 CQRS。该应用程序用于批次制造工厂,允许用户查看活动批次和已完成批次的列表,并在必要时更新批次信息。每个批次都有大量与之相关的信息,例如质量和过程测量。根据这些文章,读写数据被组织成查询和命令:
Meanwhile... on the query side of my architecture
CQRS with MediatR and AutoMapper
这是查询和查询处理程序的一个简单示例。 DataContext
使用 SimpleInjector 注入查询处理程序。
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 的范围内或短暂的生活方式。但是,当使用 transient 生活方式时,SimpleInjector 会引发以下错误,该错误是在注册类型时抛出的,如下所示:
container.Register<DataContext>();
An unhandled exception of type 'SimpleInjector.DiagnosticVerificationException' occurred in SimpleInjector.dll
Additional information: The configuration is invalid. The following diagnostic warnings were reported:
-[Disposable Transient Component] DataContext is registered as transient, but implements IDisposable.
在 SimpleInjector 网站上研究这个问题揭示了以下内容 note:
Warning: Transient instances are not tracked by the container. This means that Simple Injector will not dispose transient instances.
这让我走上了为 DataContext 使用 Lifetime Scope 生活方式的道路。为此,我为我的查询创建了一个新的装饰器 class 并将其注册如下:
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());
An unhandled exception of type 'System.InvalidOperationException' occurred in MediatR.dll
Additional information: Handler was not found for request of type MediatorTest.GetAllBatchesQuery.
Container or service locator not configured properly or handlers not registered with your container.
调试并查看 MediatR 代码后,似乎在调用 mediator.Send(...)
方法时,通过调用 [=19] 创建了 GetAllBatchesQueryHandler
class 的新实例=].但是,由于此时DataContext
不在执行范围内,可能没有正确初始化,导致异常。
我相信我了解问题的根本原因,但不知道如何有效地解决它。为了帮助更好地说明这个问题,我开发了以下最小示例。任何实现 IDisposable
的 class 都会导致与 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;
}
}
}
问题是您的装饰对象(及其 DbContext
依赖项)是在创建装饰器时创建的,并且那时没有活动范围(因为您稍后在时间)。您应该使用 here 中描述的 decoratee 工厂。换句话说,你的 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 在创建范围后推迟创建。