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("你的資料庫連結")); } }