Asp.net问题随笔: An attempt was made to use the context while it is…nce members are not guaranteed to be thread safe

用.net 5在做Vue的webapi开发的时候,一个页面调多个接口的时候就会返回这样的红色报错:An attempt was made to use the context while it is…nce members are not guaranteed to be thread safe。

查看了一下线程;两个Action使用的不一样。

//查看线程
Thread.GetCurrentProcessorId();

 

初步判断是两个接口的间隙时间太短,前一个还没完成的情况下又来一个,两个线程同时使用了EF Core的同一服务导致的不安全。

于是跟了下服务的生命周期,官方代码如下

namespace Microsoft.Extensions.DependencyInjection
{
    //
    // 摘要:
    //     Specifies the lifetime of a service in an Microsoft.Extensions.DependencyInjection.IServiceCollection.
    public enum ServiceLifetime
    {
        //
        // 摘要:
        //     Specifies that a single instance of the service will be created.
        Singleton,
        //
        // 摘要:
        //     Specifies that a new instance of the service will be created for each scope.
        //
        // 言论:
        //     In ASP.NET Core applications a scope is created around each server request.
        Scoped,
        //
        // 摘要:
        //     Specifies that a new instance of the service will be created every time it is
        //     requested.
        Transient
    }
}

 

 

解决方法是将之前Startup里用的

ServiceLifetime.Scoped 换成 ServiceLifetime.Transient;每次请求时,都创建一个服务的新实例。这样就不会冲突了。代码如下:
services.AddDbContext<MySqlDbContext>(options => options.UseMySql(connection).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking), ServiceLifetime.Transient);
services.AddTransient<IRepositoryBase, RepositoryBase>();
posted @ 2021-12-14 14:31  上山下水  阅读(224)  评论(0编辑  收藏  举报