欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-10 16:08:26
如果要在程序中使用DbContext,则需要先在Nuget中安装Microsoft.EntityFrameworkCore.SqlServer ......

如果要在程序中使用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();
            }
        }
    }
}