最近使用.net core k开发时,碰到个问题,Ef使用中程序发出了一个警告:
More than twenty 'IServiceProvider' instances have been created for internal use by Entity Framework. This is commonly caused by injection of a new singleton service instance into every DbContext instance. For example, calling UseLoggerFactory passing in a new instance each time--see https://go.microsoft.com/fwlink/?linkid=869049 for more details. Consider reviewing calls on 'DbContextOptionsBuilder' that may require new service providers to be built.
这个警告是说,我们创建了超过20个的IServiceProvider用于EF的内部使用,提醒我们程序是不是出现了问题,让我们查看DbContextOptionsBuilder是不是有问题。
本来这只是个警告,一般来说没什么问题,在好奇心的驱使下,又是百度,又是谷歌,又是MSDN,又是GitHub看源码,发现这个好像是.net ef core的一个BUG,如果置之不管,时间久了可能导致内存溢出,而且目前确认有人因为这个导致内存溢出了。
现在,我们来重现这个警告:
首先,我们创建一个控制台程序,当然也可以是api项目或者web mvc项目,然后在Nuget中安装以下包(博主使用的.net core 2.2的版本,mysql数据库):
Microsoft.EntityFrameworkCore(EF框架包)
Microsoft.Extensions.Logging.Console(控制台日志输出)
Pomelo.EntityFrameworkCore.MySql(mysql数据库连接)
Microsoft.NETCore.App(这个应该是默认会带的,没有就加上)
安装完成之后,需要创建一个数据库,随便建立一两个表,这里建两个表,对应实体如下:
using System; using System.Collections.Generic; using System.Text; namespace DemoConsole2 { public class Dept { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } } }