ABP Application Layer-Application service (application services)

Source: Internet
Author: User
Tags app service

ABP Application Layer-Application service (application services)

Click here to go to the ABP series articles General Catalogue

DDD-based Modern ASP.--ABP Series 15, ABP Application Layer-Application service (application services)

The ABP is "ASP. Boilerplate Project (ASP. NET Template project) "for short.

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

ABP's Open source project on GitHub : https://github.com/aspnetboilerplate

This article is provided by Dongguan -Heaven translation

Application services are used to expose domain (business) logic to the presentation layer. The presentation layer invokes the application service by passing in the DTO (data transfer object) parameter, and the application service executes the appropriate business logic through the domain object and returns the DTO to the presentation layer. Therefore, the presentation layer and the domain layer will be completely separated. In an ideal hierarchy project, the presentation layer should never directly access the domain object.

Iapplicationservice interface

In an ABP, an application service needs to implement the Iapplicationservice interface. The best practice is to create the appropriate interface for each app service. So, we first define an application service interface, as follows:

public interface ipersonappservice:iapplicationservice{    void Createperson (Createpersoninput input);

Ipersonappservice has only one method, it will be presented with a layer of notes to create a new person. Createpersoninput is a Dto object, as follows:

public class createpersoninput:iinputdto{    [Required] public    string Name {get; set;}    public string EmailAddress {get; set;}}

Next, we implement the Ipersonappservice interface:

public class personappservice:ipersonappservice{    private readonly irepository<person> _personrepository;    Public Personappservice (irepository<person> personrepository)    {        _personrepository = personrepository ;    }    public void Createperson (Createpersoninput input)    {        var person = _personrepository.firstordefault (p = p). EmailAddress = = input. EmailAddress);        if (person! = null)        {            throw new userfriendlyexception ("There is already a person with given email address"); 
   
    } person        = new Person {Name = input. Name, EmailAddress = input. EmailAddress};        _personrepository.insert (person);    }}
   

Here are a few important tips:

    • Personappservice performs database operations through IRepository. It is generated through the constructor injection pattern. We are using dependency injection here.
    • The Personappservice implements the Iapplicationservice (inherited Iapplicationservice through Ipersonappservice). The ABP automatically registers it with the dependency injection system and can be injected into other types.
    • The Createperson method requires a parameter of type Createpersoninput. This is an input dto that will be automatically verified by the ABP for its data validity. You can view the DTO and data Validation (Validation) documentation for details.
App Service type

The Application service (application services) needs to implement the Iapplicationservice interface. Of course, you can choose to inherit your app service (application services) from the Applicationservice base class, so your app service will naturally implement the Iapplicationservice interface. The Applicationservice base class provides convenient logging and localization capabilities. It is recommended that you create an app service base class for your application that inherits from the Applicationservice type. This way you can add some common features to provide all of your app services to use. An example of an application service is shown below:

public class Taskappservice:applicationservice, itaskappservice{public    taskappservice ()    {        Localizationsourcename = "Simpletasksystem";    }    public void CreateTask (Createtaskinput input)    {        //record log, Logger defined in Applicationservice        logger.info (" Creating a new task with description: "+ input. Description);        Gets the localized text (L is localizationhelper.getstring (...) The simple version, defined in the Applicationservice type)        var text = L ("Samplelocalizabletextkey");        Todo:add new task to database ...    }}

In this example, we define localizationsourcename in the constructor, but you can define it in the base class so that you don't need to define it in each specific application service. View logging (logging) and localization (localization) documents for more information.

Unit of work

In an ABP, an app service method defaults to a unit of work.

(1) Connection & Transaction management (for connection & transaction Management)

In the application service approach, if we need to invoke two warehousing methods, then these methods must be a transaction. As an example:

public void Createperson (Createpersoninput input) {    var person = new Person {Name = input. Name, EmailAddress = input. EmailAddress};        _personrepository.insert (person);    _statisticsrepository.incrementpeoplecount ();}

We insert a data into the person table and then modify the value of the person count field in the other table. These two operations are implemented in different warehouses, but they use the same data connections and transactions. How is this going to be achieved?

For UOW mode, the ABP automatically opens the database when the transaction starts and executes the Createperson method. At the end of the method, the transaction will be committed if no exception occurs, and ensure that the database connection is closed. Therefore, all database operations in the Createperson method are treated as a single transaction (atomicity), and the operations in those transactions are rolled back when an exception is thrown. Therefore, the two warehousing methods in the example use the same data connections and transactions.

When you call the GetAll () method in the warehouse, it returns a IQueryable. The database connection should be opened after the storage method is called. This is due to deferred execution of IQueryable and LINQ. When you invoke a similar ToList () method, the database query will actually start executing. Consider the following example:

Public searchpeopleoutput searchpeople (searchpeopleinput input) {    //Get iqueryable<person>    var query = _ Personrepository.getall ();    Filter Data    if (!string. IsNullOrEmpty (input. Searchedname)    {        query = query. Where (person = = person. Name.startswith (input. Searchedname));    }    if (input. Isactive.hasvalue)    {        query = query. Where (person = = person. IsActive = = input. Isactive.value);    }    Get paged    var people = query. Skip (input. Skipcount). Take (input. Maxresultcount). ToList ();    return new Searchpeopleoutput {people = mapper.map<list<persondto>> (People)};}

Because an application service (application services) method is a unit of work, database connections are turned on during method execution. If you call GetAll () in non-app service (application services), you need to explicitly use the work cell pattern. For example, if you want to use GetAll () in the Controller's action method or call multiple Appservice methods that have a database operation, you should use the action method with the virtual modifier and pass [Unitofwork] on the action. The display turns on the work cell mode.

Note that I used the AutoMapper library to convert the list to list. You can view the DTO documentation for details.

Translator-Heaven Note: Here to say, is the difference between UOW and non-UOW mode, the two modes for the database connection open and close is different. For the controller's method, the ABP defaults to non-UOW mode, at which point the calling method will cause an error to indicate that the database is not connected. The solution is to add virtual to the method.

(2) Automatically save data modification (for automatically saving changes)

For the unit of work Method (app service (application Services) method), the ABP will automatically save all data modifications at the end of the method. Suppose we need an app service (application services) method to update the name of a person:

public void UpdateName (Updatenameinput input) {    var person = _personrepository.get (input). PERSONID);    Person. Name = input. NewName;}

That's it, name was successfully modified! We don't even need to call the _personrepository.update method. The ORM framework keeps track of all entity modifications in the unit of work and updates the modifications to the database.

Lifecycle of application Services

The lifecycle of all application services (application services) instances is temporary (Transient). This means that a new instance of app service (application services) will be created for each use. ABP resolutely uses dependency injection technology. When an application service (application services) type needs to be injected, a new instance of the application services (application services) type is automatically created by the dependency injection container. See the dependency Injection (Dependency injection) documentation for more information.

ABP Application Layer-Application service (application services)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.