关于EFCore线程内唯一

2022-10-13,

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);
        }

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

《关于EFCore线程内唯一.doc》

下载本文的Word格式文档,以方便收藏与打印。