C# 触发Masstransit消费程序时启动新的生存时间范围
我们有以下代码来配置ReceiveEndpoint:C# 触发Masstransit消费程序时启动新的生存时间范围,c#,entity-framework,asp.net-core,autofac,masstransit,C#,Entity Framework,Asp.net Core,Autofac,Masstransit,我们有以下代码来配置ReceiveEndpoint: private Action<IServiceBusReceiveEndpointConfigurator> GetReceiveEndpointConfigurator(IEnumerable<Type> consumerTypes) { return c => { c.EnableDeadLetteringOnMessageExpiration = true;
private Action<IServiceBusReceiveEndpointConfigurator> GetReceiveEndpointConfigurator(IEnumerable<Type> consumerTypes)
{
return c =>
{
c.EnableDeadLetteringOnMessageExpiration = true;
c.SubscribeMessageTopics = false;
c.MaxDeliveryCount = 3;
c.EnableDeadLetteringOnMessageExpiration = true;
c.UseRetry(Retry.Exponential(3, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(1)));
foreach (var consumerType in consumerTypes)
{
c.Consumer(consumerType, p => _componentContext.Resolve(p));
}
};
}
它能用,但看起来不太好
有没有办法在消费者触发之前启动一个新的生命周期?或者我应该重写UnitOfWork模式以确保相同的DbContext在存储库和UnitOfWork中被重用
非常感谢您的建议您需要使用MassTransit.Autofac软件包来解析您的消费者,它将使用软件包中的AutofacScopeProvider部分来创建生存范围并解析您的消费者
显示配置,包括如何通过扫描自动发现消费者并将其添加到MassTransit
您的使用者不应使用此软件包包含任何容器代码,他们只应添加DbContext作为构造函数依赖项,并让Autofac完成工作。您需要使用MassTransit.Autofac软件包来解析您的使用者,它将使用包中的AutofacScopeProvider部分创建生存期范围并解析您的使用者
显示配置,包括如何通过扫描自动发现消费者并将其添加到MassTransit
您的用户不应该在使用此软件包的过程中包含任何容器代码,他们应该将DbContext添加为构造函数依赖项,并让Autofac完成这项工作。我不能100%确定您想要实现什么-您希望ASP.NET控制器和MassTransit用户共享特定的DbContext吗?你打算如何确保两个都使用相同的DbContext?这一点很好,@nizmow。我希望DbContext是控制器中的一个新实例,是使用者中的另一个实例。这现在不起作用,因为它注册为InstancePerLifeTimeScope。我不能100%确定您想要实现什么-您想让ASP.NET控制器和MassTransit消费者共享特定的DbContext吗?你打算如何确保两个都使用相同的DbContext?这一点很好,@nizmow。我希望DbContext是控制器中的一个新实例,是使用者中的另一个实例。这现在不起作用,因为它注册为InstancePerLifeTimeScope谢谢你的回答和一个超级棒的框架,Chris!谢谢你的回答和一个超级棒的框架,克里斯!
public async Task Consume(ConsumeContext<RetailerCreatedEvent> context)
{
using (var scope = _serviceProvider.CreateScope())
{
var unitOfWork = scope.ServiceProvider.GetRequiredService<IUnitOfWork<MyDbContext>>();
}
}