abp-官网翻译

英文官网:Documents | AspNet Boilerplate

什么是ASP.NET样板文件?
ASP.NET样板文件(ABP)是一个开源的、有良好文档记录的应用程序框架。它不仅仅是一个框架,它还提供了一个基于领域驱动设计的强大体系结构模型,并考虑了所有最佳实践。
ABP与最新的ASP.NET Core和EF Core配合使用,但也支持ASP.NET MVC 5.x和EF 6.x。

快速样品
让我们研究一个简单的类来了解ABP的好处:

public class TaskAppService : ApplicationService, ITaskAppService
{
    private readonly IRepository<Task> _taskRepository;

    public TaskAppService(IRepository<Task> taskRepository)
    {
        _taskRepository = taskRepository;
    }

    [AbpAuthorize(MyPermissions.UpdateTasks)]
    public async Task UpdateTask(UpdateTaskInput input)
    {
        Logger.Info("Updating a task for input: " + input);

        var task = await _taskRepository.FirstOrDefaultAsync(input.TaskId);
        if (task == null)
        {
            throw new UserFriendlyException(L("CouldNotFindTheTaskMessage"));
        }

        ObjectMapper.MapTo(input, task);
    }
}

这里我们看到一个示例应用程序服务方法。表示层直接使用DDD中的应用程序服务来执行应用程序的用例。将UpdateTask视为JavaScript通过AJAX调用的方法。

Let's see some of ABP's benefits here:

  • Dependency Injection: ABP uses and provides a conventional DI infrastructure. Since this class is an application service, it's conventionally registered to the DI container as transient (created per request). It can simply inject any dependencies (such as the IRepository<Task> in this sample).ABP使用并提供传统的DI基础设施。因为这个类是一个应用程序服务,所以它通常作为瞬态(根据请求创建)注册到DI容器。它可以简单地注入任何依赖项(例如本示例中的IRepository<Task>)
  • Repository: ABP can create a default repository for each entity (such as IRepository<Task> in this example). The default repository has many useful methods such as the FirstOrDefault method used in this example. We can extend the default repository to suit our needs. Repositories abstract the DBMS and ORMs and simplify the data access logic. ABP可以为每个实体创建一个默认存储库(例如本例中的IRepository<Task>)。默认存储库有许多有用的方法,例如本例中使用的FirstOrDefault方法。我们可以扩展默认存储库以满足我们的需要。存储库抽象了DBMS和ORM,简化了数据访问逻辑。
  • Authorization: ABP can check permissions declaratively. It prevents access to the UpdateTask method if the current user has no "update tasks" permission or is not logged in. ABP not only uses declarative attributes, but it also has additional ways in which you can authorize.ABP可以声明性地检查权限。如果当前用户没有“更新任务”权限或未登录,则会阻止访问UpdateTask方法。ABP不仅使用声明性属性,还提供了其他授权方式。
  • Validation: ABP automatically checks if the input is null. It also validates all the properties of an input based on standard data annotation attributes and custom validation rules. If a request is not valid, it throws a proper validation exception and handles it in the client side.ABP自动检查输入是否为空。它还基于标准数据注释属性和自定义验证规则验证输入的所有属性。如果请求无效,它将抛出一个正确的验证异常,并在客户端进行处理。
  • Audit Logging : User, browser, IP address, calling service, method, parameters, calling time, execution duration and some other information is automatically saved for each request based on conventions and configurations.用户、浏览器、IP地址、呼叫服务、方法、参数、呼叫时间、执行持续时间和一些其他信息会根据约定和配置自动为每个请求保存。
  • Unit Of Work: In ABP, each application service method is assumed to be a unit of work by default. It automatically creates a connection and begins a transaction at the beginning of the method. If the method successfully completes without an exception, then the transaction is committed and the connection is disposed. Even if this method uses different repositories or methods, all of them will be atomic (transactional). All changes on entities are automatically saved when a transaction is committed. We don't even need to call the _repository.Update(task) method as shown above.在ABP中,默认情况下,每个应用程序服务方法都假定为一个工作单元。它会自动创建一个连接,并在方法的开头开始一个事务。如果方法在没有异常的情况下成功完成,则提交事务并释放连接。即使此方法使用不同的存储库或方法,它们都将是原子的(事务性的)。提交事务时,将自动保存对实体的所有更改。我们甚至不需要调用_repository.Update(task)方法,如上所示。
  • Exception Handling: We almost never have to manually handle exceptions in ABP on a web application. All exceptions are automatically handled by default! If an exception occurs, ABP automatically logs it and returns a proper result to the client. For example, if this is an AJAX request, it returns a JSON object to the client indicating that an error occurred. It hides the actual exception from the client unless the exception is a UserFriendlyException, as used in this sample. It also understands and handles errors on the client side and show appropriate messages to the users.我们几乎不必在web应用程序的ABP中手动处理异常。默认情况下会自动处理所有异常!如果发生异常,ABP将自动记录该异常,并向客户端返回正确的结果。例如,如果这是一个AJAX请求,它将向客户端返回一个JSON对象,指示发生了错误。它对客户机隐藏实际异常,除非异常是UserFriendlyException,如本示例中所用。它还可以理解和处理客户端的错误,并向用户显示适当的消息。
  • Logging: As you see, we can write logs using the Logger object defined in the base class. Log4Net is used by default, but it's changeable and configurable.如您所见,我们可以使用基类中定义的Logger对象编写日志。默认情况下使用Log4Net,但它是可更改和可配置的。
  • Localization: Note that we used the 'L' method while throwing the exception? This way, it's automatically localized based on the current user's culture. See the localization document for more.请注意,我们在抛出异常时使用了“L”方法?这样,它会根据当前用户的文化自动本地化。有关更多信息,请参阅本地化文档。
  • Auto Mapping: In the last line, we map input using the MapTo method of ABP's IObjectMapper. properties to entity properties. It uses the AutoMapper library to perform the mapping. We can easily map properties from one object to another based on naming conventions.在最后一行中,我们使用ABP的IObjectMapper的MapTo方法映射输入。属性转换为实体属性。它使用AutoMapper库来执行映射。我们可以根据命名约定轻松地将属性从一个对象映射到另一个对象。
  • Dynamic API Layer: TaskAppService is a simple class, actually. We generally have to write a wrapper API Controller to expose methods to JavaScript clients, but ABP automatically does that on runtime. This way, we can use application service methods directly from clients.实际上,TaskAppService是一个简单的类。我们通常必须编写一个包装器API控制器来向JavaScript客户端公开方法,但ABP会在运行时自动这样做。这样,我们可以直接从客户端使用应用程序服务方法。
  • Dynamic JavaScript AJAX Proxy : ABP creates proxy methods that make calling application service methods as simple as calling JavaScript methods on the client. ABP创建代理方法,使调用应用程序服务方法与在客户机上调用JavaScript方法一样简单。

我们可以在这个简单的类中看到ABP的好处。所有这些任务通常都需要很长的时间,但都是由框架自动处理的。
除了这个简单的例子之外,ABP还为模块化、多租户、缓存、后台作业、数据过滤器、设置管理、域事件、单元和集成测试等提供了强大的基础设施和开发模型。。。你专注于你的商业代码,不要重复你自己!

 

 

开发应用程序
创建任务实体
我想从一个简单的任务实体开始。由于实体是域层的一部分,我将其添加到.Core项目中:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using Abp.Timing;

namespace Acme.SimpleTaskApp.Tasks
{
    [Table("AppTasks")]
    public class Task : Entity, IHasCreationTime
    {
        public const int MaxTitleLength = 256;
        public const int MaxDescriptionLength = 64 * 1024; //64KB

        [Required]
        [StringLength(MaxTitleLength)]
        public string Title { get; set; }

        [StringLength(MaxDescriptionLength)]
        public string Description { get; set; }

        public DateTime CreationTime { get; set; }

        public TaskState State { get; set; }

        public Task()
        {
            CreationTime = Clock.Now;
            State = TaskState.Open;
        }

        public Task(string title, string description = null)
            : this()
        {
            Title = title;
            Description = description;
        }
    }

    public enum TaskState : byte
    {
        Open = 0,
        Completed = 1
    }
}

我从ABP的基本实体类派生而来,默认情况下,该类包含Id属性int。我们可以使用通用版本Entity<TPrimaryKey>,来选择不同的PK类型。
IHasCreationTime是一个简单的接口,它只定义CreationTime属性(最好使用CreationTime的标准名称)。
任务实体定义必需的标题和可选描述。
TaskState是定义任务状态的简单枚举。
时钟。现在返回日期时间。默认情况下现在返回。但是它提供了一个抽象,所以如果需要的话,我们可以很容易地在特性中切换到DateTime.UtcNow。在使用ABP框架时,请始终使用Clock.Now而不是DateTime.Now。
我想将任务实体存储到数据库中的AppTasks表中。

Adding Task to DbContext

.EntityFrameworkCore project includes a pre-defined DbContext. I should add a DbSet for the Task entity into the DbContext:

public class SimpleTaskAppDbContext : AbpDbContext
{
    public DbSet<Task> Tasks { get; set; }

    public SimpleTaskAppDbContext(DbContextOptions<SimpleTaskAppDbContext> options) 
        : base(options)
    {

    }
}

现在,EF Core知道我们有一个任务实体。
创建第一个数据库迁移
我们将创建初始数据库迁移,以创建数据库和AppTasks表。我从Visual Studio打开包管理器控制台并运行添加迁移命令(默认项目必须是.EntityFrameworkCore项目):

Entity Framework Core Add Migration

此命令在.EntityFrameworkCore项目中创建一个Migrations文件夹,其中包括一个迁移类和数据库模型的快照:

EF Core initial migration

 

posted @ 2021-11-24 16:52  vba是最好的语言  阅读(395)  评论(0编辑  收藏  举报