.net core控制台程序中使用原生依赖注入

如果要在程序中使用DbContext,则需要先在Nuget中安装Microsoft.EntityFrameworkCore.SqlServer

 

using ConsoleApp1.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using ConsoleApp1.BusinessLogic;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Startup();
            Console.WriteLine("Hello World!");
        }

        private static void Startup()
        {
            var services = new ServiceCollection();
            var connectionString = "Data Source=localhost;Initial Catalog=TestDB;User ID=sa;Password=123;";
            services.AddDbContext(options => options.UseSqlServer(connectionString));

            services.AddScoped();
            var provider = services.BuildServiceProvider();
            using (var serviceScope = provider.CreateScope())
            {
                var serviceProvider = serviceScope.ServiceProvider;
                var databaseBO = serviceProvider.GetService();
                databaseBO.GenerateData();
            }
        }
    }
}

 

你可能感兴趣的:(.net core控制台程序中使用原生依赖注入)