我的代码里将IServiceProvider放入ServiceLocator中遇到的问题。
方案1:Microsoft.Extensions.DependencyInjection1.0 每次获取IServiceProvider 需要_services.BuildServiceProvider(); ;其中private static IServiceCollection _services; 为静态。
方案2:Microsoft.Extensions.DependencyInjection2.0 每次获取IServiceProvider 直接取IServiceProvider的静态属性; 其中public static IServiceProvider ServiceProvider { get; private set; }为静态。
EF6项目中使用Microsoft.Extensions.DependencyInjection1.0 时,用方案1正确,用方案2会出现内存泄露。
使用EF Core1.0时(强依赖于Microsoft.Extensions.DependencyInjection1.0),用方案1正确,用方案2会出现内存泄露。
使用EF Core2.0时(强依赖于Microsoft.Extensions.DependencyInjection2.0),用方案2正确,用方案1会出现内存泄露。
使用EF Core2.0且用方案1时,可以把官方扩展方法AddDbContext替换为以下代码避免出现内存泄露:
var options = new DbContextOptionsBuilder<XXDbContext>().UseSqlServer("connstr").Options;
services.AddScoped(s => new XXDbContext(options));
建议:使用EF Core2.0+方案2。