官术网_书友最值得收藏!

Registering the context in services (.NET Core DI)

The dependency injection support in the ASP.NET framework came too late for the .NET developers/architects who were seeking shelter from third-party tools such as Ninject, StructureMap, Castle Windsor, and so on. Finally, we gained support from ASP.NET Core. It has most of the features from the third-party DI providers, but the only difference is the configuration should happen inside the Startup.cs middleware.

First thing's first, let's configure the connection string in our new appSettings.json:

    "ConnectionStrings": {
"DefaultConnection": "Server
(localdb)\\mssqllocaldb;Database=MasteringEFCoreBlog;
Trusted_Connection=True;MultipleActiveResultSets=true"
},

Then configure the context as a service (all service configuration goes into Startup.cs). To support that, import MasteringEFCore.Web.Data and Microsoft.EntityFrameworkCore in the Startup class. Finally, add the DbContext to the services collection by creating and including DbContextOptionsBuilder using UseSqlServer():

    public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<BlogContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("
DefaultConnection"
)));
services.AddMvc();
}

We will be using a lightweight version of SQL Server called LocalDB for development. This edition was created with the intention of development, so we shouldn't be using it in any other environments. It runs with very minimal configuration, so it's invoked while running the application. The .mdf database file is stored locally. 

We have configured the database context using dependency injection, and at this stage, we are good to go. We are almost there. As of now, we have the schema required for the database and the context for EF and services being configured. All of these will end up providing an empty database with literally no values in it. Run the application and see that an empty database is created. It will be of no use. In the next section, let's see how we can seed the database with master data/create tables with sample data, which can be consumed by the application.

主站蜘蛛池模板: 新野县| 天峨县| 文成县| 昌乐县| 双峰县| 南陵县| 灵台县| 灵川县| 永胜县| 永靖县| 靖安县| 钟山县| 沁源县| 武胜县| 个旧市| 彝良县| 澜沧| 汶上县| 芦山县| 旺苍县| 彰化市| 榆树市| 石屏县| 花莲市| 卓资县| 眉山市| 仁怀市| 天镇县| 连江县| 本溪| 洛川县| 洞口县| 蕲春县| 思南县| 台湾省| 昭通市| 无为县| 沙雅县| 柞水县| 翁源县| 平湖市|