internal class Program { static void Main(string[] args) { // 创建服务集合 var services = new ServiceCollection(); // 注入 services.AddScoped<IMyService, MyService>(); // 配置服务 ConfigureServices(services); // 创建服务提供者 var serviceProvider = services.BuildServiceProvider(); // 获取DbContext实例 using (var db = serviceProvider.GetRequiredService<YouDbContext>()) { var data = db.Database.SqlQuery<TableModel>($"select * from Table").ToList(); } //or 获取服务实例 var services = serviceProvider.GetService<IMyService>(); services.Execute(); } private static void ConfigureServices(IServiceCollection services) { services.AddDbContext<CfwDbContext>(options => options.UseSqlServer("你的数据库链接")); } }
标签:获取,serviceProvider,var,实例,static,services,NET,控制台 From: https://www.cnblogs.com/linshuli/p/18232463