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

使用.NET 6开发TodoList应用之引入数据存储的思路详解

程序员文章站 2022-06-16 11:32:38
需求作为后端crud程序员(bushi,数据存储是开发后端服务一个非常重要的组件。对我们的todolist项目来说,自然也需要配置数据存储。目前的需求很简单: 需要能持久化todolist对象并...

需求

作为后端crud程序员(bushi,数据存储是开发后端服务一个非常重要的组件。对我们的todolist项目来说,自然也需要配置数据存储。目前的需求很简单:

  • 需要能持久化todolist对象并对其进行操作;
  • 需要能持久化todoitem对象并对其进行操作;

问题是,我们打算如何存储数据?

存储组件的选择非常多:以mssql server/postgres/mysql/sqlite等为代表的关系型数据库,以mongodb/elasticsearch等为代表的非关系型数据库,除此之外,我们还可以在开发阶段选择内存数据库,在云上部署的时候还可以选择类似azure cosmos db/aws dynamodb以及云上提供的多种关系型数据库。

应用程序使用数据库服务,一般都是借助成熟的第三方orm框架,而在.net后端服务开发的过程中,使用的最多的两个orm框架应该是:entityframeworkcoredapper,相比之下,efcore的使用率更高一些。所以我们也选择efcore来进行演示。

目标

在这篇文章中,我们仅讨论如何实现数据存储基础设施的引入,具体的实体定义和操作后面专门来说。

  • 使用mssql server容器作为数据存储组件(前提是电脑上需要安装docker环境,下载并安装docker desktop即可);

这样选择的理由也很简单,对于使用mac的小伙伴来说,使用容器来启动mssql server可以避免因为非windows平台导致的示例无法运行的问题。

原理和思路

因为我们对开发环境和生产环境的配置有差异,那先来看看共性的部分:

  • 引入efcore相关的nuget包并进行配置;
  • 添加dbcontext对象并进行依赖注入;
  • 修改相关appsettings.{environment}.json文件;
  • 主程序配置。
  • 本地运行mssql server容器并实现数据持久化;

同上一篇一样,和具体的第三方对接的逻辑我们还是放到infrastructure里面去,应用程序中只保留对外部服务的抽象操作。

实现

1. 引入nuget包并进行配置

需要在infrastructure项目中引入以下nuget包:

microsoft.entityframeworkcore.sqlserver

# 第二个包是用于使用powershell命令(add-migration/update-database/...)需要的,如果使用eftool,可以不安装这个包。
microsoft.entityframeworkcore.tools

为了使用eftool,需要在api项目中引入以下nuget包:

microsoft.entityframeworkcore.design

2. 添加dbcontext对象并进行配置

在这一步里,我们要添加的是一个具体的dbcontext对象,这对于有经验的开发者来说并不是很难的任务。但是在具体实现之前,我们可以花一点时间考虑一下现在的clean architecture结构:我们的目的是希望除了infrastructure知道具体交互的第三方是什么,在application以及domain里都要屏蔽底层的具体实现。换言之就是需要在infrastrcuture之外的项目中使用接口来做具体实现的抽象,那么我们在application中新建一个common/interfaces文件夹用于存放应用程序定义的抽象接口iapplicationdbcontext

namespace todolist.application.common.interfaces;

public interface iapplicationdbcontext
{
    task<int> savechangesasync(cancellationtoken cancellationtoken);
}

接下来在infrastructure项目中新建persistence文件夹用来存放和数据持久化相关的具体逻辑,我们在其中定义dbcontext对象并实现刚才定义的接口。

using microsoft.entityframeworkcore;
using todolist.application.common.interfaces;

namespace todolist.infrastructure.persistence;

public class todolistdbcontext : dbcontext, iapplicationdbcontext
{
    public todolistdbcontext(dbcontextoptions<todolistdbcontext> options) : base(options)
    {
    }
}

这里的处理方式可能会引起困惑,这个iapplicationdbcontext存在的意义是什么。这里的疑问和关于要不要使用repository模式有关,国外多位大佬讨论过这个问题,即repository是不是必须的。可以简单理解大家达成的共识是:不是必须的,如果不是有某些特别的数据库访问逻辑,或者有足够的理由需要使用repository模式,那就保持架构上的简洁,在application层的多个cqrs handlers中直接注入该iapplicationdbcontext去访问数据库并进行操作。如果需要使用repository模式,那在这里就没有必要定义这个接口来使用了,application中只需要定义irepository<t>,在infrastructure中实现的baserepository中访问dbcontext即可。

我们后面是需要使用repository的,是因为希望演示最常用的开发模式,但是在这一篇中我保留iapplicationdbconetxt的原因是也希望展示一种不同的实现风格,后面我们还是会专注到repository上的。

需要的对象添加好了,下一步是配置dbcontext,我们还是遵循当前的架构风格,在infrastructure项目中添加dependencyinjection.cs文件用于添加所有第三方的依赖:

using microsoft.entityframeworkcore;
using microsoft.extensions.configuration;
using microsoft.extensions.dependencyinjection;
using todolist.application.common.interfaces;
using todolist.infrastructure.persistence;

namespace todolist.infrastructure;

public static class dependencyinjection
{
    public static iservicecollection addinfrastructure(this iservicecollection services, iconfiguration configuration)
    {
        services.adddbcontext<todolistdbcontext>(options =>
            options.usesqlserver(
                configuration.getconnectionstring("sqlserverconnection"),
                b => b.migrationsassembly(typeof(todolistdbcontext).assembly.fullname)));

        services.addscoped<iapplicationdbcontext>(provider => provider.getrequiredservice<todolistdbcontext>());

        return services;
    }
}

3. 配置文件修改

我们对appsettings.development.json文件进行配置:

{
  "logging": {
    "loglevel": {
      "default": "information",
      "microsoft.aspnetcore": "warning"
    }
  },
  "usefiletolog": true,
  "connectionstrings": {
    "sqlserverconnection": "server=localhost,1433;database=todolistdb;user id=sa;password=strongpwd123;"
  }
}

这里需要说明的是如果是使用mssql server默认端口1433的话,连接字符串里是可以不写的,但是为了展示如果使用的不是默认端口应该如何配置,还是显式写在这里了供大家参考。

4. 主程序配置

api项目中,我们只需要调用上面写好的扩展方法,就可以完成配置。

var builder = webapplication.createbuilder(args);

// add services to the container.
builder.configurelog();

builder.services.addcontrollers();
builder.services.addendpointsapiexplorer();
builder.services.addswaggergen();

// 添加基础设施配置
builder.services.addinfrastructure(builder.configuration);

// 省略以下...

5. 本地运行mssql server容器及数据持久化

在保证本地docker环境正常启动之后,运行以下命令:

# 拉取mssql镜像
$ docker pull mcr.microsoft.com/mssql/server:2019-latest
2019-latest: pulling from mssql/server
7b1a6ab2e44d: already exists 
4ffe416cf537: pull complete 
fff1d174f64f: pull complete 
3588fd79aff7: pull complete 
c8203457909f: pull complete 
digest: sha256:a098c9ff6fbb8e1c9608ad7511fa42dba8d22e0d50b48302761717840ccc26af
status: downloaded newer image for mcr.microsoft.com/mssql/server:2019-latest
mcr.microsoft.com/mssql/server:2019-latest

# 创建持久化存储
$ docker create -v /var/opt/mssql --name mssqldata  mcr.microsoft.com/mssql/server:2019-latest /bin/true
3c144419db7fba26398aa45f77891b00a3253c23e9a1d03e193a3cf523c66ce1

# 运行mssql容器,挂载持久化存储卷
$ docker run -d --volumes-from mssqldata --name mssql -e 'accept_eula=y' -e 'sa_password=strongpwd123' -p 1433:1433 mcr.microsoft.com/mssql/server:2019-latest
d99d774f70229f688d71fd13e90165f15abc492aacec48de287d348e047a055e

# 确认容器运行状态
$ docker ps
container id   image                                        command                  created          status          ports                    names
d99d774f7022   mcr.microsoft.com/mssql/server:2019-latest   "/opt/mssql/bin/perm…"   24 seconds ago   up 22 seconds   0.0.0.0:1433->1433/tcp   mssql

验证

为了验证我们是否可以顺利连接到数据库,我们采用添加migration并在程序启动时自动进行数据库的migration方式进行:

首先安装工具:

dotnet tool install --global dotnet-ef
# dotnet tool update --global dotnet-ef

# 生成migration
$ dotnet ef migrations add setupdb -p src/todolist.infrastructure/todolist.infrastructure.csproj -s src/todolist.api/todolist.api.csproj
build started...
build succeeded.
[17:29:15 inf] entity framework core 6.0.1 initialized 'todolistdbcontext' using provider 'microsoft.entityframeworkcore.sqlserver:6.0.1' with options: migrationsassembly=todolist.infrastructure, version=1.0.0.0, culture=neutral, publickeytoken=null 
done. to undo this action, use 'ef migrations remove'

为了在程序启动时进行自动migration,我们向infrastructure项目中增加一个文件applicationstartupextensions.cs并实现扩展方法:

using microsoft.aspnetcore.builder;
using microsoft.entityframeworkcore;
using microsoft.extensions.dependencyinjection;
using todolist.infrastructure.persistence;

namespace todolist.infrastructure;

public static class applicationstartupextensions
{
    public static void migratedatabase(this webapplication app)
    {
        using var scope = app.services.createscope();
        var services = scope.serviceprovider;

        try
        {
            var context = services.getrequiredservice<todolistdbcontext>();
            context.database.migrate();
        }
        catch (exception ex)
        {
            throw new exception($"an error occurred migrating the db: {ex.message}");
        }
    }
}

并在api项目的program.cs中调用扩展方法:

// 省略以上...
app.mapcontrollers();

// 调用扩展方法
app.migratedatabase();

app.run();

最后运行主程序:

$ dotnet run --project src/todolist.api
building...
[17:32:32 inf] entity framework core 6.0.1 initialized 'todolistdbcontext' using provider 'microsoft.entityframeworkcore.sqlserver:6.0.1' with options: migrationsassembly=todolist.infrastructure, version=1.0.0.0, culture=neutral, publickeytoken=null 
[17:32:32 inf] executed dbcommand (22ms) [parameters=[], commandtype='text', commandtimeout='30']
select 1
[17:32:32 inf] executed dbcommand (19ms) [parameters=[], commandtype='text', commandtimeout='30']
select object_id(n'[__efmigrationshistory]');
[17:32:32 inf] executed dbcommand (3ms) [parameters=[], commandtype='text', commandtimeout='30']
select 1
[17:32:32 inf] executed dbcommand (2ms) [parameters=[], commandtype='text', commandtimeout='30']
select object_id(n'[__efmigrationshistory]');
[17:32:33 inf] executed dbcommand (4ms) [parameters=[], commandtype='text', commandtimeout='30']
select [migrationid], [productversion]
from [__efmigrationshistory]
order by [migrationid];
[17:32:33 inf] applying migration '20211220092915_setupdb'.
[17:32:33 inf] executed dbcommand (4ms) [parameters=[], commandtype='text', commandtimeout='30']
insert into [__efmigrationshistory] ([migrationid], [productversion])
values (n'20211220092915_setupdb', n'6.0.1');
[17:32:33 inf] now listening on: https://localhost:7039
[17:32:33 inf] now listening on: http://localhost:5050
[17:32:33 inf] application started. press ctrl+c to shut down.
[17:32:33 inf] hosting environment: development
[17:32:33 inf] content root path: /users/yu.li1/projects/asinta/blogs/cnblogs/todolist/src/todolist.api/

使用数据库工具连接容器数据库,可以看到migration已经成功地写入数据库表__efmigrationshistory了:

使用.NET 6开发TodoList应用之引入数据存储的思路详解

本篇文章仅完成了数据存储服务的配置工作,目前还没有添加任何实体对象和数据库表定义,所以暂时没有可视化的验证,仅我们可以运行程序看我们的配置是否成功:

总结

在本文中,我们探讨并实现了如何给.net 6 web api项目添加数据存储服务并进行配置,下一篇开始将会深入数据存储部分,定义实体,构建repository模式和seeddata等操作。

除了本文演示的最基础的使用方式意外,在实际使用的过程中,我们可能会遇到类似:为多个dbcontext分别生成migrations或者为同一个dbcontext根据不同的环境生成不同database provider适用的migrations等情况,扩展阅读如下,在这里就不做进一步的演示了,也许以后有机会可以单独写篇实践指南:

使用多个提供程序进行迁移

使用单独的迁移项目

参考资料

entityframeworkcore

使用多个提供程序进行迁移

使用单独的迁移项目

到此这篇关于使用.net 6开发todolist应用之引入数据存储的文章就介绍到这了,更多相关.net 6开发todolist引入数据存储内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!