手把手教你用Abp vnext構建API接口服務

ABP是一個開源應用程序框架,該項目是ASP.NET Boilerplate Web應用程序框架的下一代,專一於基於ASP.NET Core的Web應用程序開發,也支持開發控制檯應用程序。git

官方網站:https://abp.io/
官方文檔:https://docs.abp.io/程序員

1、使用ABP框架能夠快速的搭建一個應用程序,僅須要幾步便可完成:

1. 安裝ABP CLI

ABP CLI是使用ABP框架啓動新解決方案的最快方法。若是沒有安裝ABP CLI,使用命令行窗口安裝ABP CLI:github

dotnet tool install -g Volo.Abp.Cli

2. 在一個空文件夾中使用abp new命令建立您的項目:

abp new Acme.BookStore

您可使用不一樣級別的名稱空間。例如BookStore,Acme.BookStore或Acme.Retail.BookStore。web

這樣,就已經完成了一個應用程序的搭建。
sql

而後咱們只須要修改一下其餘的配置便可運行應用程序,開發人員在這個架構的基礎上就能夠愉快的擼代碼了。數據庫

然而,ABP的學習纔剛剛開始。ABP放棄了原有MVC的架構,使用了模塊化架構,支持微服務,根據DDD模式和原則設計和開發,爲應用程序提供分層模型。對於沒有微服務開發經驗的程序員來講,學習ABP難度比較大。下面咱們開始從一個空的web解決方案,一步步搭建API接口服務。json

2、用APB基礎架構搭建一個用戶中心API接口服務

開發環境:Mac Visual Studio Code
SDK:dotnet core 3.1api

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 四、緩存、微服務等。

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

相關文章
相關標籤/搜索