The domain event domain events_ Basic application of Domain layer in ABP framework is detailed

Source: Internet
Author: User
Tags eventbus

In C #, a class can define its own events and other classes can register the event and listen for events that can be notified when the event is triggered. This is useful for desktop applications or stand-alone Windows service. However, there is a problem with Web applications because objects are created based on requests (request) and their lifecycle is short-lived. It is difficult for us to register other categories of events. Similarly, the direct registration of other categories of events also creates a coupling between classes.

In application systems, domain events are used to decouple and reuse (re-use) business logic.

Event Bus
The event bus is a monomer (singleton) object that is shared by all other classes and can be used to trigger and handle events. To use this event bus, you need to refer to it. You can do this in two ways:

Get the default instance (getting the instance)

You can use Eventbus.default directly. It is a global event bus and can be used in the following ways:

EventBus.Default.Trigger (...); Triggering events

Inject Ieventbus event interface (injecting Ieventbus)

In addition to using Eventbus.default directly, you can use the method of dependency injection (DI) to obtain Ieventbus references. This facilitates unit testing. Here, we use the paradigm of attribute injection:

 public class Taskappservice:applicaservice {public
  ieventbus Eventbus {get; set;}
  Public Taskappservice () {
   eventbus = nulleventbus.instance;
  }
 }

Injecting the event bus, it is more suitable to use attribute injection than construction sub injection. The event is described by the class and the event object inherits from the EventData. Suppose we want to trigger an event after a task completes:

 public class Taskcompletedeventdata:eventdata {public
  int TaskId {get; set;}
 }

This class contains attributes that are required by the class to handle the event. The EventData class defines the EventSource (that object triggers the event) and the Eventtime (when triggered) property.

Defining events
ABP defines the Abphandledexceptiondata event and automatically triggers the event when the exception occurs. This is especially useful when you want to get more information about the exception (even if ABP has automatically logged all the exceptions). You can register this event and set its trigger time when the anomaly occurs.

ABP also provides a number of common event data classes for entity changes: Entitycreatedeventdata, Entityupdatedeventdata, and Entitydeletedeventdata. They are defined in the Abp.Events.Bus.Entitis namespace. When an entity is added/updated/deleted, these events are automatically triggered by ABP. If you have a person entity, you can register to Entitycreatedeventdata, and the event is triggered after the new person entity is created and inserted into the database. These events also support inheritance. If the student class inherits from the person class, and you register into Entitycreatedeventdata, you will then receive the trigger when the person or student is added.

Triggering events
examples of triggering events are as follows:

 public class Taskappservice:applicationservice {public
  ieventbus Eventbus {get; set;}
  Public Taskappservice () {
   eventbus = nulleventbus.instance;
  }

  public void Completetask (Completetaskinput input) {
   //todo: Tasks on the completed database
   Eventbus.trigger (new taskcompletedeventdata {TaskId = n});
  }
 

Here are some overloads of the triggering method:

 Eventbus.trigger<taskcompletedeventdata> (new Taskcompletedeventdata {TaskId =});
 Eventbus.trigger (this, new Taskcompletedeventdata {TaskId =});
 Eventbus.trigger (typeof (Taskcompletedeventdata), this, new Taskcompletedeventdata {TaskId = 42});

Event handling
to handle the event, you should implement the Ieventhandler interface as shown below:

 public class Activitywriter:ieventhandler<taskcompletedeventdata> itransientdependency {public
  void Handleevent (Taskcompletedeventdata eventdata) {
   writeactivity ("A task is completed by id =" + eventdata.taskid); 
   
    }
 }

   

The Eventbus has been integrated into the dependency injection system. As we implemented itransientdependency in the previous example, when the Taskcompleted event is triggered, it creates a new entity of the Activitywriter class and calls its Handleevent method, and then releases it. See the article on Dependency Injection (DI) for details.

1. Treatment of the underlying event (handling base events)

Eventbus supports the inheritance of events. For example, you can create taskeventdata and two inheriting classes: Taskcompletedeventdata and Taskcreatedeventdata:

 public class Taskeventdata:eventdata {public
  task task {get; set;}
 }

 public class Taskcreatedeventdata:taskeventdata {public
  User creatoruser {get; set;}
 }

 public class Taskcompletedeventdata:taskeventdata {public
  User completoruser {get; set;}
 }

However, you can implement Ieventhandler to handle these two events:

 public class Activitywriter:ieventhandler<taskeventdata> itransientdependency {public
  void handleevent ( Taskeventdata eventdata) {
   if (EventData is Taskcreatedeventdata) {
   ...
   } else{...}}}
 

Of course, you can also implement Ieventhandler to handle all the events, if you really want to do so (the author does not recommend this way).

2. Handling multiple incidents (handling multiple events)

We can handle multiple events in a single processor (handler). At this point, you should implement Ieventhandler for different events. Examples are as follows:

 public class Activitywriter:
  ieventhandler<taskcompletedeventdata>,
  ieventhandler< Taskcreatedeventdata>,
  itransientdependency
 {public
  void Handleevent (taskcompletedeventdata EventData) {
   //todo: Handling Event
  } public
  void Handleevent (Taskcreatedeventdata eventdata) {
   //todo: Handling Events
  }
 }

Registering the processor
We must register the processor (handler) into the event bus to handle the event.

1. Automatic type automatically

ABP scans all classes that implement the Ieventhandler interface and registers them automatically into the event bus. When an event occurs, it obtains the processor (handler) Reference object by relying on injection (DI) and releases the event after it has been processed. This is the recommended way to use the event bus in ABP.

2. Manual type (manually)

You can also register events by hand, but there are some problems. In a Web application, the registration of an event should be when the application is started. When a Web request (request) arrives, the event is registered, and the behavior is repeated. This may cause problems with your application because the registered class can be invoked multiple times. It is also necessary to note that manual enrollment cannot be used with the dependency injection system.

ABP provides overloads of multiple event bus enrollment methods (overload). One of the simplest overloaded methods is to wait for a delegate (delegate) or a lambda.

 Eventbus.register<taskcompletedeventdata> (eventdata =>
  {
   writeactivity ("A task is completed by id =" + eventdata.taskid);
  

So, the event: The task completed will occur, and this lambda method will be invoked. The second overloaded method waits for an object that implements the Ieventhandler:

Eventbus.register<taskcompletedeventdata> (New Activitywriter ());

The same example, if Activitywriter is invoked because of an event. This method also has a non-generic overload. Another overload accepts two parameters that are generalized:

Eventbus.register<taskcompletedeventdata, activitywriter> ();
At this point, the event bus creates a new activitywriter in each event. When it is released, it invokes the Activitywriter.dispose method.

Finally, you can register an event-processor factory (handler factory) to be responsible for creating the processor. The processor factory has two methods: GetHandler and Releasehandler, examples are as follows:

public class Activitywriterfactory:ieventhandlerfactory {public
  Ieventhandler gethandler () {return
   new Activitywriter ();
  }
  public void Releasehandler (Ieventhandler handler) {
   //todo: Releasing Activitywriter entity (processor)
  }
 }

ABP also provides a special factory class, Iochandlerfactory, which iochandlerfactory can be used to create or release (Dispose) processors via a dependency injection system. ABP can automate the registration of Iochandlerfactory. Therefore, if you want to use a dependency injection system, please use the automated registration method directly.

Unregister event
When you register the event bus manually, you may want to unregister later. The simplest way to unregister an event is registration. Dispose (). Examples are as follows:

Register an event
Var registration = eventbus.register<taskcompletedeventdata> (eventdata => writeactivity ("a Task is completed by id = "+ eventdata.taskid)";
Unregister an event
registration. Dispose ();

Of course, cancellation can be done anywhere at any time. Save (keep) The registered object and release (Dispose) it when you want to cancel the registration. Overloads of all enrollment methods (overload) return an object that can be released (disposable) to cancel the registration of the event.

The event bus also provides the unregister method. Use Example:

Create a processor
var handler = new Activitywriter ();
Register an event
eventbus.register<taskcompletedeventdata> (handler);
Cancels the registration
eventbus.unregister<taskcompletedeventdata> (handler) of this event;

It also provides overloaded methods to unregistered delegates and factories. The unregister processor object must be the same as the previously registered object.

Finally, Eventbus provides a UnregisterAll () method to cancel the registration of all processors for an event, while the UnregisterAll () method is all the processors for all events.

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.