.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<MyDbContext>(options => options.UseSqlServer(connectionString));

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

 

posted @ 2019-12-13 17:46  欧阳.NET  阅读(621)  评论(1编辑  收藏  举报