当前位置: 移动技术网 > IT编程>开发语言>.net > 关于EFCore线程内唯一

关于EFCore线程内唯一

2019年11月15日  | 移动技术网IT编程  | 我要评论

magi魔笛,侍从官之肩,死神574

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

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网