Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use ABP Framework based on ASP.NET MVC

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use the ABP framework based on ASP.NET MVC, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

Why use ABP

In recent years, we have developed a number of Web applications and desktop applications, the requirements are simple or complex, or elegant or ugly. A basic fact is that we have only accumulated some experience or increased our familiarity with NET.

With the continuous increase of software development experience, we find that a lot of work is repetitive and mechanical, and with the continuous improvement of software complexity, it is no longer feasible to rely on experience to complete some simple additions, deletions, modifications and queries. In particular, the requirements of users are getting higher and higher, and they want to add more and more functions. at present, this development mode has been stretched. It's hard for me to imagine how to continuously integrate multiple systems and add some new features in the existing mode.

When developing a system, we will inevitably use a variety of frameworks. Data persistence layer implementation, logging, ASP.NET MVC, IOC and automatic mapping. A high-quality software system often has components such as global fault tolerance, message queue and so on.

When these components are put together, their complexity increases sharply. With the general technical level of individuals and small teams, it is difficult to design a balanced and coordinated framework. I am also very skeptical about the traditional so-called three-tier structure. (the three-tier architecture created by a programmer with a monthly salary of 15k, which I have read carefully, is also full of problems and does not explain why it is used.)

In fact, we just want to focus most of our attention on the business implementation when programming. Don't think too much about the basic software structure. There should be a frame or paradigm to provide basic services such as logging, fault tolerance, and AOP,DI.

Slightly more formal companies have formed their own internal software framework after years of precipitation, and they do not start from a blank when developing software. Instead, it was built on a very solid foundation. This greatly improves the speed of development, and an architecture often determines the mode of division of labor and cooperation. At present, the fundamental reason why we are unable to divide the labor and cooperate is the lack of a mature and stable infrastructure and workflow.

At present, there are many open source frameworks on .NET. Such as Apworks and ABP. Apworks is an open source framework written by the Chinese. It is a fully functional, not only can write distributed applications, but also can write desktop applications. The full name of ABP is Asp.net boilerplate project (asp.net model project). Is a very active open source project on github. It does not use any new technology, but two architects integrate some of the tools commonly used in asp.net development together, and partially implement the concept of DDD. It is an out-of-the-box framework and can be used as a good starting point for asp.net distributed applications.

Of course, there is a price for using the framework. You have to be invaded by the strong API of the framework, or you have to use his dialect. And this framework wants to eat thoroughly, but also have to pay a lot of learning costs. But the benefits are also obvious. The industry's top architects have built an infrastructure for you, responded well to questions about how a software system should be designed and planned, and provided a set of best practices and examples.

Although there is a cost to learn, after a long journey, we have stood on the threshold of industrial development from ignorance. Based on this framework, we can divide tasks, unit testing and so on. The probability of BUG in the software is greatly reduced.

Create an empty web application from a template

ABP's official website: http://www.aspnetboilerplate.com

ABP's open source project on Github: https://github.com/aspnetboilerplate

ABP provides a startup template for new projects (although you can create the project manually and get the ABP package from nuget, the template is easier).

Go to www.aspnetboilerplate.com/Templates to create your application from the template.

You can choose SPA (AngularJs or DurandalJs) or the MPA (classic multi-page application) project. You can choose Entity Framework or NHibernate as the ORM framework.

Here we select AngularJs and Entity Framework, fill in the project name "SimpleTaskSystem", click the "CREATE MY PROJECT" button to download a zip package, unzip it and get the VS2013 solution, using .NET version 4.5.1.

Abp components and other third-party components are referenced in each project and need to be downloaded from Nuget.

The yellow exclamation mark icon indicates that this component does not exist in the local folder and needs to be restored from the Nuget. Do the following:

To get the project up and running, you also have to create a database. This template assumes that you are using SQL2008 or newer versions. Of course, it can also be easily replaced with other relational databases.

Open the Web.Config file to view and configure the link string:

The copy code is as follows:

(when Code first data migration for EF is used later, a database named SimpleTaskSystemDb is automatically created in the SQL Server database. )

In this way, the project is ready to run! Open VS2013 and press F5:

This simple task system program will be implemented step by step.

Create solid

Write entity classes in the Core project because entities are part of the domain layer.

A simple application scenario: create tasks (tasks) and assign them to people. We need both Task and Person entities.

The Task entity has several attributes: description (Description), creation time (CreationTime), task status (State), and optional navigation attribute (AssignedPerson) to reference the Person.

Public class Task: Entity {ForeignKey ("AssignedPersonId")] public virtual Person AssignedPerson {get; set;} public virtual int? AssignedPersonId {get; set;} public virtual string Description {get; set;} public virtual DateTime CreationTime {get; set;} public virtual TaskState State {get; set;} public Task () {CreationTime = DateTime.Now; State = TaskState.Active;}}

The Person entity is simpler, defining only one Name attribute:

Public class Person: Entity {public virtual string Name {get; set;}}

In the ABP framework, there is an Entity base class that has an Id attribute. Because the Task class inherits from Entity, it has an Id of type long. The Person class has an Id of type int because the int type is the default type of the Entity base class Id, and when no specific type is specified, the Id of the entity is the int type.

Create DbContext

To use EntityFramework, you need to define the DbContext class first. The template of ABP has created the DbContext file. We just need to add the Task and Person classes to IDbSet. Please see the code:

Public class SimpleTaskSystemDbContext: AbpDbContext {public virtual IDbSet Tasks {get; set;} public virtual IDbSet People {get; set;} public SimpleTaskSystemDbContext (): base ("Default") {} public SimpleTaskSystemDbContext (string nameOrConnectionString): base (nameOrConnectionString) {}}

Create database tables through Database Migrations

We use EntityFramework's Code First schema to create a database schema. The project generated by ABP template has the data migration feature enabled by default. We modify the Configuration.cs file under the Migrations folder under the SimpleTaskSystem.EntityFramework project:

Internal sealed class Configuration:

DbMigrationsConfiguration {public Configuration () {AutomaticMigrationsEnabled = false;} protected override void Seed (SimpleTaskSystem.EntityFramework.SimpleTaskSystemDbContext context) {context.People.AddOrUpdate (p = > p.Name, new Person {Name = "Isaac Asimov"}, new Person {Name = "Thomas More"}, new Person {Name = "George Orwell"}, new Person {Name = "Douglas Adams"});}

In the package Manager console window at the bottom of VS2013, select the default project and execute the command "Add-Migration InitialCreate"

A xxxx-InitialCreate.cs file is generated under the Migrations folder, with the following contents:

Public partial class InitialCreate: DbMigration {public override void Up () {CreateTable ("dbo.StsPeople", c = > new {Id = c.Int (nullable: false, identity: true), Name = c.String (),}) .PrimaryKey (t = > t.Id) CreateTable ("dbo.StsTasks", c = > new {Id = c.Long (nullable: false, identity: true), AssignedPersonId = c.Int (), Description = c.String (), CreationTime = c.DateTime (nullable: false), State = c.Byte (nullable: false) ) .PrimaryKey (t = > t.Id) .ForeignKey ("dbo.StsPeople", t = > t.AssignedPersonId) .Index (t = > t.AssignedPersonId) } public override void Down () {DropForeignKey ("dbo.StsTasks", "AssignedPersonId", "dbo.StsPeople"); DropIndex ("dbo.StsTasks", new [] {"AssignedPersonId"}); DropTable ("dbo.StsTasks"); DropTable ("dbo.StsPeople");}}

Then continue to execute "Update-Database" in the package Manager console, which automatically creates the corresponding data table in the database:

PM > Update-Database

The database is shown as follows:

(after modifying the entity, you can execute Add-Migration and Update-Database again, and you can easily synchronize the database structure with the entity class.)

Define warehousing interface

Through the warehousing mode, we can better separate the business code from the database operation code, and we can have different implementation classes for different databases, but the business code does not need to be modified.

The code that defines the warehousing interface is written to the Core project because the warehousing interface is part of the domain layer.

Let's first define the warehousing interface of Task:

Public interface ITaskRepository: IRepository {List GetAllWithPeople (int? AssignedPersonId, TaskState? State);}

It inherits from the IRepository generic interface in the ABP framework.

Common addition, deletion, modification and search methods have been defined in IRepository:

So ITaskRepository has the above methods by default. You can add its unique method GetAllWithPeople (...).

There is no need to create a repository class for the Person class, because the default method is sufficient. ABP provides a way to inject generic repositories, as you'll see in the TaskAppService class in the section "creating Application Services" later.

Implement the warehouse class

We will implement the ITaskRepository warehousing interface defined above in the EntityFramework project.

The project created through the template has defined a repository base class: SimpleTaskSystemRepositoryBase (this is a good practice because you can add general methods to this base class later).

Public class TaskRepository: SimpleTaskSystemRepositoryBase, ITaskRepository {public List GetAllWithPeople (int? AssignedPersonId, TaskState? State) {/ / in the warehousing method, the ABP framework does not have to deal with database connections, DbContext, and data transactions. Var query = GetAll (); / / GetAll () returns an IQueryable interface type / / add some Where conditions if (assignedPersonId.HasValue) {query = query.Where (task = > task.AssignedPerson.Id = = assignedPersonId.Value);} if (state.HasValue) {query = query.Where (task = > task.State = = state) } return query .OrderByDescending (task = > task.CreationTime) .include (task = > task.AssignedPerson) .ToList ();}}

TaskRepository inherits from SimpleTaskSystemRepositoryBase and implements the ITaskRepository interface defined above.

Create an application service (Application Services)

Define the application service in the Application project. First, define the interface of the application service layer of Task:

Public interface ITaskAppService: IApplicationService {GetTasksOutput GetTasks (GetTasksInput input); void UpdateTask (UpdateTaskInput input); void CreateTask (CreateTaskInput input);}

ITaskAppService inherits from IApplicationService,ABP to automatically provide some functional features (such as dependency injection and parameter validation) for this class.

Then, we write the TaskAppService class to implement the ITaskAppService interface:

Public class TaskAppService: ApplicationService, ITaskAppService {private readonly ITaskRepository _ taskRepository; private readonly IRepository _ personRepository; / the constructor automatically injects the class or interface we need / public TaskAppService (ITaskRepository taskRepository, IRepository personRepository) {_ taskRepository = taskRepository; _ personRepository = personRepository;} public GetTasksOutput GetTasks (GetTasksInput input) {/ / call the specific method of Task repository GetAllWithPeople var tasks = _ taskRepository.GetAllWithPeople (input.AssignedPersonId, input.State) / automatically convert List to List return new GetTasksOutput {Tasks = Mapper.Map (tasks)} with AutoMapper;} public void UpdateTask (UpdateTaskInput input) {/ / can Logger directly, which is the Logger.Info defined in the ApplicationService base class ("Updating a task for input:" + input) / obtain the Task entity object var task = _ taskRepository.Get (input.TaskId) of the specified Id through the general method Get of the warehouse base class; / / modify the attribute value of the task entity if (input.State.HasValue) {task.State = input.State.Value;} if (input.AssignedPersonId.HasValue) {task.AssignedPerson = _ personRepository.Load (input.AssignedPersonId.Value) } / / none of us need to call the Update method / / because the method in the application service layer turns on the unit of work mode (Unit of Work) by default / / the ABP framework automatically saves all changes to the entity when the unit of work is complete, unless an exception is thrown. It will be rolled back automatically when there is an exception, because the database transaction is turned on by default in the unit of work. } public void CreateTask (CreateTaskInput input) {Logger.Info ("Creating a task for input:" + input); / / create a new Task entity var task = new Task {Description = input.Description} by entering parameters; if (input.AssignedPersonId.HasValue) {task.AssignedPersonId = input.AssignedPersonId.Value;} / / call the Insert method of the repository base class to save the entity to the database _ taskRepository.Insert (task);}}

TaskAppService uses warehousing for database operations, which leads to constructor injection references to the repository object.

Data verification

If the parameter object of the application service (Application Service) method implements the IInputDto or IValidate interface, ABP automatically verifies the validity of the parameters.

The CreateTask method has a CreateTaskInput parameter, which is defined as follows:

Public class CreateTaskInput: IInputDto {public int? AssignedPersonId {get; set;} [Required] public string Description {get; set;}}

The Description attribute specifies that it is required through annotations. Other Data Annotation features can also be used.

If you want to use custom authentication, you can implement the ICustomValidate interface:

Public class UpdateTaskInput: IInputDto, ICustomValidate {[Range (1, long.MaxValue)] public long TaskId {get; set;} public int? AssignedPersonId {get; set;} public TaskState? State {get; set;} public void AddValidationErrors (List results) {if (AssignedPersonId = = null & & State = = null) {results.Add (new ValidationResult ("AssignedPersonId and State cannot be empty at the same time!", new [] {"AssignedPersonId", "State"});}

You can write custom validation code in the AddValidationErrors method.

Create a Web Api service

ABP can easily publish the public method of Application Service as a Web Api interface, which can be called by clients through ajax.

DynamicApiControllerBuilder .ForAll (Assembly.GetAssembly (typeof (SimpleTaskSystemApplicationModule)), "tasksystem") .build ()

All classes in the SimpleTaskSystemApplicationModule assembly that inherit the IApplicationService interface will automatically create a corresponding ApiController, and the exposed methods will be converted to WebApi interface methods.

It can be called through a routed address such as http://xxx/api/services/tasksystem/Task/GetTasks.

Through the above case, this paper briefly introduces the usage of domain layer, infrastructure layer and application service layer.

Now you can call the Application Service method directly in the Action method of ASP.NET MVC's Controller.

If you use SPA single-page programming, you can directly call the corresponding Application Service method on the client side through ajax (by creating a dynamic Web Api).

Thank you for reading this article carefully. I hope the article "how to use the ABP Framework based on ASP.NET MVC" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report