.net core控制台程序中使用原生依赖注入
程序员文章站
2023-10-28 19:30:40
如果要在程序中使用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(); } } } }
推荐阅读