我创建了一个 .net Core 控制台应用程序,并添加了以下依赖项注入包:
Microsoft.Extensions.DependencyInjection
要注入 EF Core DbContext 服务,以下是该项目的代码片段:
static void Main(string[] args)
{
// Create service collection and configure our services
var services = ConfigureServices();
// Generate a provider
var serviceProvider = services.BuildServiceProvider();
// Kick off our actual code
serviceProvider.GetService<Startup>().Run();
}
public static IConfiguration LoadConfiguration()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddEnvironmentVariables();
return builder.Build();
}
private static IServiceCollection ConfigureServices()
{
IServiceCollection services = new ServiceCollection();
// Set …Run Code Online (Sandbox Code Playgroud) c# dependency-injection dbcontext entity-framework-core .net-core