UnitOfWork和DbContext:使用DI

时间:2019-04-04 12:40:07

标签: entity-framework dependency-injection .net-core thread-safety unit-of-work

我正在使用一个托管IHostedService的.NET Core 2.2控制台应用程序:

public class MqttClientHostedService : IHostedService, IDisposable
{
    [...]
    public MqttClientHostedService(
        ILogger<MqttClientHostedService> logger, 
        IOptions<MqttClientConfiguration> mqttConfiguration, 
        IPositionService positionService)
    {
        this.logger = logger;
        this.config = mqttConfiguration;
        this.positionService = positionService;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        mqttClient = new MqttFactory().CreateMqttClient();
        mqttClient.Connected += async (s, e) => await MqttClient_Connected(s, e);
        mqttClient.ApplicationMessageReceived +=
            async (s, e) => await MqttClient_ApplicationMessageReceived(s, e);

        await mqttClient.ConnectAsync(
            new MqttClientOptionsBuilder()
                .WithTcpServer(config.Value.Host, config.Value.Port).Build());
    }

    private async Task MqttClient_ApplicationMessageReceived(
        object sender, MqttApplicationMessageReceivedEventArgs e)
    {
        string message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
        await positionService.HandleMessage(message);
    }

    [...]
}

IPositionService是一位经理,负责检查邮件并检查邮件是否可以保存在我们的数据库中:

public class PositionService : IPositionService
{
    [...]

    public PositionService(
        IUnitOfWork unitOfWork, ILogger<PositionService> logger)
    {
        this.unitOfWork = unitOfWork;
        this.logger = logger;
    }

    public async Task HandleMessage(string message)
    {
        Entity entity = await unitOfWork.EntityRepository.GetByMessage(message);

        [...]

        await unitOfWork.EntityRepository.UpdateAsync(entity);
        await unitOfWork.Save();
    }

    [...]
}

IUnitOfWork是Entity Framework Core DbContext的包装(请不要判断我,我有这样做的理由):

public class UnitOfWork : IUnitOfWork
{
    [...]

    public UnitOfWork(MyContext myContext)
    {
        this.myContext = myContext;

        EntityRepository = new EFRepository<Entity>(myContext);
    }

    public async Task Save()
    {
        await myContext.SaveChangesAsync();
    }
}
实现EFRepository<T>接口的

IRepository<T>DbSet<T>的包装(同样,请不要评判我)。这里没有相关代码。

控制台应用程序的Program.cs的配置如下:

[...]
.ConfigureServices((hostContext, services) =>
{
    services.AddDbContext<MyContext>(
        c => c.UseSqlServer("[...]", options => options.UseNetTopologySuite()),
        ServiceLifetime.Transient);

    services.AddTransient<IPositionService, PositionService>();
    services.AddTransient(typeof(IRepository<>), typeof(EFRepository<>));
    services.AddTransient<IUnitOfWork, UnitOfWork>();

    services.AddHostedService<MqttClientHostedService>();

    [...]
});

问题是PositionService.HandleMessage每秒被调用很多次,并且DbContext不是线程安全的,我收到此错误消息:

  

在此之前,第二个操作在此上下文上开始   完成。

我通过从IUnitOfWork的依赖项中删除PositionService,注入IServiceScopeFactory并执行以下操作来解决此问题:

using (IServiceScope serviceScope = serviceScopeFactory.CreateScope())
{
    IUnitOfWork unitOfWork = serviceScope.ServiceProvider.GetService<IUnitOfWork>();

    [...]
}

这种方式有效,但我不喜欢它。这似乎是一个把戏,我不喜欢我的PositionService知道Dependency Injection并且必须处理范围这一事实。

我的问题是:有一种更好的方法可以解决这个问题而又不影响我的课程?我应该使整个UnitOfWork线程安全吗?或者也许不用DI手工创建它?

1 个答案:

答案 0 :(得分:2)

问题的根源在于,MyContext在以下对象图中被俘虏为俘虏依赖性:

MqttClientHostedService
    -> PositionService
        -> UnitOfWork
            -> MyContext 

此图中的所有类型都注册为Transient,但是,在托管服务(例如您的MqttClientHostedService)中,仅解析一次的时间为应用程序并不确定地缓存。这实际上使他们成为单身人士。

换句话说,MyContext偶然被单个MqttClientHostedService保持活动,并且由于可以并行出现多个消息,因此您处于竞争状态。

解决方案是让每个ApplicationMessageReceived事件在其自己的唯一小气泡(作用域)中运行,并从该气泡中解析一个新的IPositionService。例如:

public class MqttClientHostedService : IHostedService, IDisposable
{
    [...]
    public MqttClientHostedService(
        ILogger<MqttClientHostedService> logger, 
        IOptions<MqttClientConfiguration> mqttConfiguration, 
        IServiceProvider provider)
    {
        this.logger = logger;
        this.config = mqttConfiguration;
        this.provider = provider;
    }
    [...]
    private async Task MqttClient_ApplicationMessageReceived(
        object sender, MqttApplicationMessageReceivedEventArgs e)
    {
        using (var scope = provider.CreateScope())
        {
            positionService = scope.ServiceProvider
                .GetRequiredService<IPositionService>();
            string message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
            await positionService.HandleMessage(message);
        }
    }

    [...]
}