.NET控制台获取依赖注入实例
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("你的数据库链接")); } }