Loading

手把手教你用Abp vnext构建API接口服务

ABP是一个开源应用程序框架,该项目是ASP.NET Boilerplate Web应用程序框架的下一代,专注于基于ASP.NET Core的Web应用程序开发,也支持开发控制台应用程序。

官方网站:https://abp.io/
官方文档:https://docs.abp.io/

一、使用ABP框架可以快速的搭建一个应用程序,仅需要几步即可完成:

1. 安装ABP CLI

ABP CLI是使用ABP框架启动新解决方案的最快方法。如果没有安装ABP CLI,使用命令行窗口安装ABP CLI:

dotnet tool install -g Volo.Abp.Cli

2. 在一个空文件夹中使用abp new命令创建您的项目:

abp new Acme.BookStore

您可以使用不同级别的名称空间。例如BookStore,Acme.BookStore或Acme.Retail.BookStore。

这样,就已经完成了一个应用程序的搭建。

然后我们只需要修改一下其他的配置即可运行应用程序,开发人员在这个架构的基础上就可以愉快的撸代码了。

然而,ABP的学习才刚刚开始。ABP放弃了原有MVC的架构,使用了模块化架构,支持微服务,根据DDD模式和原则设计和开发,为应用程序提供分层模型。对于没有微服务开发经验的程序员来说,学习ABP难度比较大。下面我们开始从一个空的web解决方案,一步步搭建API接口服务。

二、用APB基础架构搭建一个用户中心API接口服务

开发环境:Mac Visual Studio Code
SDK:dotnet core 3.1

1. 首先我们创建一个文件夹Lemon.UserCenter,并在终端中打开该文件夹。

使用命令创建一个空的web方案:

dotnet new web -o Lemon.UserCenter.HttpApi.Hosting

2. 再使用命令创建其他类库方案:

创建api层
dotnet new classlib -o Lemon.UserCenter.HttpApi
创建应用层
dotnet new classlib -o Lemon.UserCenter.Application
创建领域层
dotnet new classlib -o Lemon.UserCenter.Domain
创建基于EntityFrameworkCore的数据层
dotnet new classlib -o Lemon.UserCenter.EntityFrameworkCore

3. 把所有类库加入解决方案,然后类库间互相引用:

创建解决方案
dotnet new sln
所有类库加入解决方案
dotnet sln Lemon.UserCenter.sln add Lemon.UserCenter.HttpApi.Hosting/Lemon.UserCenter.HttpApi.Hosting.csproj
dotnet sln Lemon.UserCenter.sln add Lemon.UserCenter.HttpApi/Lemon.UserCenter.HttpApi.csproj
dotnet sln Lemon.UserCenter.sln add Lemon.UserCenter.Application/Lemon.UserCenter.Application.csproj
dotnet sln Lemon.UserCenter.sln add Lemon.UserCenter.Domain/Lemon.UserCenter.Domain.csproj
dotnet sln Lemon.UserCenter.sln add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj
添加项目引用
dotnet add Lemon.UserCenter.HttpApi.Hosting/Lemon.UserCenter.HttpApi.Hosting.csproj reference Lemon.UserCenter.HttpApi/Lemon.UserCenter.HttpApi.csproj
dotnet add Lemon.UserCenter.HttpApi.Hosting/Lemon.UserCenter.HttpApi.Hosting.csproj reference Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj
dotnet add Lemon.UserCenter.HttpApi/Lemon.UserCenter.HttpApi.csproj reference Lemon.UserCenter.Application/Lemon.UserCenter.Application.csproj
dotnet add Lemon.UserCenter.Application/Lemon.UserCenter.Application.csproj reference Lemon.UserCenter.Domain/Lemon.UserCenter.Domain.csproj
dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj reference Lemon.UserCenter.Domain/Lemon.UserCenter.Domain.csproj

4. 在领域层新增实体。

领域层添加Volo.Abp.Identity.Domain包引用:

dotnet add Lemon.UserCenter.Domain/Lemon.UserCenter.Domain.csproj package Volo.Abp.Identity.Domain

创建领域层模块类:

using Volo.Abp.Identity;
using Volo.Abp.Modularity;

namespace Lemon.UserCenter.Domain
{
    [DependsOn(typeof(AbpIdentityDomainModule))]
    public class UserCenterDomainModule : AbpModule
    {
        
    }
}

创建实体类:

using System;
using Volo.Abp.Domain.Entities;

namespace Lemon.UserCenter.Domain
{
    public class UserData : Entity<Guid>
    {
        /// <summary>
        /// 账号
        /// </summary>
        /// <value>The account.</value>
        public string Account { get; set; }

        /// <summary>
        /// 昵称
        /// </summary>
        /// <value>The name of the nike.</value>
        public string NickName { get; set; } = "";

        /// <summary>
        /// 头像
        /// </summary>
        /// <value>The head icon.</value>
        public string HeadIcon { get; set; } = "";

        /// <summary>
        /// 手机号码
        /// </summary>
        /// <value>The mobile.</value>
        public string Mobile { get; set; } = "";

        /// <summary>
        /// 电子邮箱
        /// </summary>
        /// <value>The email.</value>
        public string Email { get; set; } = "";

        /// <summary>
        /// 删除注记
        /// </summary>
        /// <value><c>true</c> if deleted; otherwise, <c>false</c>.</value>
        public bool Deleted { get; set; }
    }
}

5. 创建数据层

数据层添加引用:

dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj package Volo.Abp.EntityFrameworkCore
dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj package Volo.Abp.EntityFrameworkCore.PostgreSQL
dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj package Microsoft.EntityFrameworkCore.Design
dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj package Microsoft.EntityFrameworkCore
dotnet add Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj package Microsoft.EntityFrameworkCore.Relational

在这里我们使用的是PostgreSQL数据库,所以引用了Volo.Abp.EntityFrameworkCore.PostgreSQL,如果使用的是MySQL,就要引用Volo.Abp.EntityFrameworkCore.MySQL,如果使用的是sqlserver,就要引用Volo.Abp.EntityFrameworkCore.SQLServer。

加入UserCenterDbContext类:

using Lemon.UserCenter.Domain;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;

namespace Lemon.UserCenter.EntityFrameworkCore
{
    [ConnectionStringName("Default")]
    public class UserCenterDbContext : AbpDbContext<UserCenterDbContext>
    {
        public DbSet<UserData> UserData { get; set; }
        
        public UserCenterDbContext(DbContextOptions<UserCenterDbContext> options)
            : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }

    }
}

加入UserCenterDbContextFactory类:

using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace Lemon.UserCenter.EntityFrameworkCore
{
    public class UserCenterDbContextFactory: IDesignTimeDbContextFactory<UserCenterDbContext>
    {
        public UserCenterDbContext CreateDbContext(string[] args)
        {
            var configuration = BuildConfiguration();

            var builder = new DbContextOptionsBuilder<UserCenterDbContext>()
                .UseNpgsql(configuration.GetConnectionString("Default"));

            return new UserCenterDbContext(builder.Options);
        }

        private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false);

            return builder.Build();
        }
    }
}

加入appsettings.json配置,用于生成数据迁移代码:

{
    "ConnectionStrings": {
      "Default": "server=127.0.0.1;port=5432;Database=abp-samples-user-center;uid=postgres;pwd=123456"
    }
}

创建数据层模块类:

using Lemon.UserCenter.Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.PostgreSql;
using Volo.Abp.Modularity;

namespace Lemon.UserCenter.EntityFrameworkCore
{
    [DependsOn(typeof(UserCenterDomainModule),
        typeof(AbpEntityFrameworkCoreModule),
        typeof(AbpEntityFrameworkCorePostgreSqlModule))]
    public class UserCenterentityFrameworkCoreModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            context.Services.AddAbpDbContext<UserCenterDbContext>(options => {
                options.AddDefaultRepositories(includeAllEntities: true);
            });

            Configure<AbpDbContextOptions>(options =>
            {
                options.Configure(ctx =>
                {
                    if (ctx.ExistingConnection != null)
                    {
                        ctx.DbContextOptions.UseNpgsql(ctx.ExistingConnection);
                    }
                    else
                    {
                        ctx.DbContextOptions.UseNpgsql(ctx.ConnectionString);
                    }
                });
            });

            #region 自动迁移数据库

            context.Services.BuildServiceProvider().GetService<UserCenterDbContext>().Database.Migrate();

            #endregion 自动迁移数据库
        }
    }
}

生成数据迁移代码:

dotnet ef migrations add InitialCreate --project Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj

在数据层下生成一个Migrations文件夹,里面的代码就是数据迁移代码,执行以下命令即可在数据库中自动生成数据库表:

dotnet ef database update --project Lemon.UserCenter.EntityFrameworkCore/Lemon.UserCenter.EntityFrameworkCore.csproj

6. 在应用层实现具体业务逻辑

应用层添加Volo.Abp.Identity.Application应用:

dotnet add Lemon.UserCenter.Application/Lemon.UserCenter.Application.csproj package Volo.Abp.Identity.Application

创建应用层模块类:

using Volo.Abp.Modularity;
using Volo.Abp.Identity;

namespace Lemon.UserCenter.Application
{
    [DependsOn(typeof(AbpIdentityApplicationModule))]
    public class UserCenterApplicationModule : AbpModule
    {
        
    }
}

创建用户接口:

using System.Threading.Tasks;
using Lemon.UserCenter.Domain;

namespace Lemon.UserCenter.Application
{
    public interface IUserService
    {
         Task<UserData> Create(UserData data);
    }
}

实现用户服务:

using System;
using System.Threading.Tasks;
using Lemon.UserCenter.Domain;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Lemon.UserCenter.Application
{
    public class UserService : ApplicationService, IUserService
    {
        private readonly IRepository<UserData, Guid> _repository;
        public UserService(IRepository<UserData, Guid> repository)
        {
            this._repository = repository;
        }

        public async Task<UserData> Create(UserData data)
        {
            return await _repository.InsertAsync(data);
        }
    }
}

7. 在api层实现webapi控制器

api层添加Volo.Abp.Identity.HttpApi引用:

dotnet add Lemon.UserCenter.HttpApi/Lemon.UserCenter.HttpApi.csproj package Volo.Abp.Identity.HttpApi

创建模块类:

using Lemon.UserCenter.Application;
using Volo.Abp.Identity;
using Volo.Abp.Modularity;

namespace Lemon.UserCenter.HttpApi
{
    [DependsOn(typeof(AbpIdentityHttpApiModule),
    typeof(UserCenterApplicationModule))]
    public class UserCenterHttpApiModule : AbpModule
    {
        
    }
}

创建controller:

using System.Threading.Tasks;
using Lemon.UserCenter.Application;
using Lemon.UserCenter.Domain;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;

namespace Lemon.UserCenter.HttpApi.Controllers
{
    [Route("api/user")]
    public class UserController : AbpController
    {
        private readonly IUserService _userService;
        public UserController(IUserService userService)
        {
            this._userService = userService;
        }

        [HttpPost("create")]
        public async Task<IActionResult> Create(UserData data)
        {
            var result = await _userService.Create(data);
            return Json(result);
        }
    }
}

7. 在api hosting实现项目启动项

添加Volo.Abp.Autofac引用:

dotnet add Lemon.UserCenter.HttpApi.Hosting/Lemon.UserCenter.HttpApi.Hosting.csproj package Volo.Abp.Autofac

创建模块类

using Lemon.UserCenter.Domain;
using Lemon.UserCenter.EntityFrameworkCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Autofac;
using Volo.Abp.Modularity;

namespace Lemon.UserCenter.HttpApi.Hosting
{
    [DependsOn(typeof(UserCenterHttpApiModule),
                typeof(UserCenterDomainModule),
                typeof(UserCenterentityFrameworkCoreModule),
                typeof(AbpAspNetCoreMvcModule),
                typeof(AbpAutofacModule))]
    public class UserCenterHttpApiHostingModule: AbpModule
    {
        public override void OnApplicationInitialization(
            ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();
            var env = context.GetEnvironment();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();
            app.UseRouting();
            app.UseMvcWithDefaultRouteAndArea();
        }
    }
}

修改Program类,新增UseAutofac:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace Lemon.UserCenter.HttpApi.Hosting
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                }).UseAutofac();
    }
}

修改Startup类:

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Lemon.UserCenter.HttpApi.Hosting
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddApplication<UserCenterHttpApiHostingModule>();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.InitializeApplication();
        }
    }
}

8. 运行服务

cd Lemon.UserCenter.HttpApi.Hosting
dotnet watch run

9. 最后我们用postman来测试api接口服务是否可以正常使用。

操作如下图:

数据库结果如下:

总结

以上就是接口服务的构建过程,主要参考了ABP CLI生成的项目结构,但是又有所不同。整个分层架构还可以继续优化,这个就见仁见智吧。后续还会继续分享ABP的相关知识,例如identity server 4、缓存、微服务等。

GitHub: https://github.com/huangmingji/abp-samples

posted @ 2020-03-17 17:10  黄明基  阅读(10618)  评论(10编辑  收藏  举报