欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

关于EFCore线程内唯一

程序员文章站 2023-10-29 12:22:16
EntityFramework的线程内唯一 EntityFramework的线程内唯一是通过httpcontext来实现的 EntityFrameworkCore的线程内唯一 我们都知道.net Core的数据库上下文对象是在容器里注册,在用到的时候通过依赖注入创建的,那要如何保证每次请求只创建一个 ......

entityframework的线程内唯一

entityframework的线程内唯一是通过httpcontext来实现的

            public static dbcontext dbcontext()  
            {  
                dbcontext dbcontext = httpcontext.current.items["dbcontext"] as dbcontext;  
                if (dbcontext == null)  
                {  
                    dbcontext = new webentities();  
                    httpcontext.current.items["dbcontext"] =  dbcontext;  
                }  
                return dbcontext;  
            }   

entityframeworkcore的线程内唯一

我们都知道.net core的数据库上下文对象是在容器里注册,在用到的时候通过依赖注入创建的,那要如何保证每次请求只创建一个对象呢?
我们可以在注册的时候,通过设置servicelifetime属性来达到目的。

            services.adddbcontext<mycontext>(options =>
            {
                // var connectionstring = configuration["connectionstrings:defaultconnection"];
                var connectionstring = configuration.getconnectionstring("defaultconnection");
                options.usesqlite(connectionstring);
            },servicelifetime.scoped);

通过查看adddbcontext这个方法我们可以发现,servicelifetime这个属性默认就是每次请求创建一次

        public static iservicecollection adddbcontext<tcontext>([notnull] this iservicecollection servicecollection, [canbenull] action<dbcontextoptionsbuilder> optionsaction = null, servicelifetime                     contextlifetime = servicelifetime.scoped, servicelifetime optionslifetime = servicelifetime.scoped) where tcontext : dbcontext
        {
            return servicecollection.adddbcontext<tcontext, tcontext>(optionsaction, contextlifetime, optionslifetime);
        }

所以我们完全不需要手动去指定(^▽^)