magi魔笛,侍从官之肩,死神574
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; }
我们都知道.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); }
所以我们完全不需要手动去指定(^▽^)
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Blazor server side 自家的一些开源的, 实用型项目的进度之 CEF客户端
.NET IoC模式依赖反转(DIP)、控制反转(Ioc)、依赖注入(DI)
vue+.netcore可支持业务代码扩展的开发框架 VOL.Vue 2.0版本发布
网友评论