C # Programming Practice-eventbroker Simple implementation

Source: Internet
Author: User

Objective

Say Eventbroker this thing is not fresh, remember the first contact with this thing is in the second company, the company's product infrastructure layer integration of distributed messaging middleware, Using the Eventbroker pattern in the. NET Foundation service layer to assemble messages into events that support the same domain, cross-domain, and cross-machine event publishing and subscriptions, it was later known that the thing was called Eventbroker. Admittedly, this is a very clever thing, it internally encapsulates the processing of messages and events, decoupling the events of the upper application from the dependencies of the delegates, and provides a very concise way to develop them. OK, this article only implements a simplified version of the Eventbroker, the functionality is very limited, and there is no integration of messaging components, so it does not support cross-domain and cross-machine distributed applications, and even without rigorous testing (such as concurrent processing, cross-threading, etc.), the community better implementation of a lot. So must declare: just experimental code, pure practiced hand, with the attitude of learning to write code, coding not easy, we do not like to spray

Get ready

This article mainly uses. NET C # technology, including delegation, reflection, weak references, and weak event patterns, writing code is also to learn these, find a sense of code. Note: In order not to affect the reading, the code has some castration, such as the need for source, follow-up I put the attachment, but this source really nothing, I upload is to do a record, stored down

Ideas

Ideas do not need to say, online search will have a lot of information, I am more lazy, directly affixed to a map on the web can clearly show the system's interactive scene and interactive process

Application

Using Eventbroker at the application level requires that the register be used for objects in the application, and typically large projects using IOC containers provide for the injection of features at object creation time, such as:

Model Code private void Onobjectbuild (ObjectModel Builder, object instance) {    var broker = dicontainer.resolve< Ieventbroker> ();    Broker. Register (instance);}

This is convenient to avoid the manual register in the program, but I'm just a simple implementation, not involving the IOC and any design thing, after registering the object, in our class can be implemented as follows:

[Eventpublication ("Topic://eventbreaker/winform/message", Eventscope = eventscope.local)]public Event EventHandler <EventModelArgs<string>> messagearrived;

The above is the event definition, we can define the method of the event delegate reference in another class, and the two do not depend on each other completely

[Eventsubscription ("Topic://eventbreaker/winform/message", Eventscope = eventscope.local)]public void Messagereceived (object sender, eventmodelargs<string> message) {    PrintOut (message). Data);}
Source
    • Source directory structure, to see if it is more streamlined than other versions?

    • Eventbroker, I'll call this. Event bus, internal package Eventtopic, event Publisher and subscriber information are stored indirectly on the bus, in addition, the bus to the outside to provide a unified API interface, convenient to call, the relevant interface is as follows:
Namespace tinyeventbroker{public class Eventbroker {private readonly eventtopiccollection topics        = new Eventtopiccollection ();            <summary>///Event Topic Collection List///</summary> public eventtopiccollection Topics {        get {return topics;}  }///<summary>//Event scenario///</summary> public virtual Eventscope Eventscope {get        {return eventscope.local;}}             <summary>////Inject the object onto the event bus///</summary> public void Register (object target) { BindingFlags bingdings = BindingFlags.Instance | bindingflags.static | BindingFlags.Public |            BindingFlags.NonPublic;            Registerpublication (target, bingdings);        Registersubscription (target, bingdings); }///<summary>//Registration Publisher///</summary> private void Registerpublication (Object t Arget, BindingFlags bindings) {//...}        <summary>///Registered Subscribers///</summary>/<param name= "target" ></param> <param name= "bindings" ></param> private void Registersubscription (object target, BindingFlags bi    ndings) {//...} }}
    • Eventtopic, which I call the event topic, a topic can contain multiple publishers and subscribers and provide some processing, the topic manager internally bridges events and dynamically invokes subscriber methods, with the following interfaces:
public class eventtopic{Public eventtopic () {} public Eventtopic (string name): the This () {this}.    name = name;    }///<summary>///Event Subject ID///</summary> public string Name {get; set;}    Private list<eventpublication> Publishers = new list<eventpublication> (); <summary>///Publisher list///</summary> internal list<eventpublication> Publishers {G        ET {return publishers;}    set {publishers = value;}    } Private list<eventsubscription> subscribers = new list<eventsubscription> ();        <summary>///Subscriber list///</summary> internal list<eventsubscription> subscribers {        get {return subscribers;}    set {subscribers = value;}    }///<summary>//Add publisher///</summary> internal void Addpublication (eventpublication publisher) {EventContext.Instance.WriteTo ("Subject: {0} Add publisher {1}", Name, publisher);       Publisher.        Eventfired + = oneventfired; Publishers.    Add (publisher); }///<summary>//Add Subscribers///</summary> internal void addsubscription (Eventsubscription subscribe        R) {EventContext.Instance.WriteTo ("Subject: {0} Add subscriber {1}", Name, subscriber); Subscribers.    ADD (subscriber); }///<summary>//Remove Publishers///</summary> internal void removepublication (Eventpublication publishe        R) {EventContext.Instance.WriteTo ("Subject: {0} Remove publisher {1}", Name, publisher); Publishers.    Remove (publisher); }///<summary>//Remove Subscribers///</summary> internal void removesubscription (Eventsubscription subscr        Iber) {EventContext.Instance.WriteTo ("Subject: {0} Remove subscriber {1}", Name, subscriber); Subscribers.    Remove (subscriber);    } internal void oneventfired (eventpublication publication, object sender, EventArgs args) {//...} private void Checkinvalidpublications () {//.......    } private void Checkinvalidsubscriptions () {//...}}
    • Publisher, subscriber, uses a weak reference to store the target object, preventing the target object from being released causing a memory leak
Using system;using system.collections.generic;using system.linq;using system.reflection;using System.Text;using System.threading.tasks;namespace tinyeventbroker{//<summary>//publishers///</summary> internal CL eventpublication {//<summary>///Weak Reference object wrapper///</summary> private Readon        ly WeakReference Wrapper;        <summary>///Event name///</summary> private readonly string eventName;        <summary>///Event handling delegate type///</summary> private readonly type eventhandletype;        <summary>///object name for displaying//</summary> private readonly string targetName; <summary>///Events definition, event for bridging objects///</summary> public event Topiceventhandler Eventfi        Red           Public Eventpublication (Object target, string eventName) {wrapper = new WeakReference (target); This.eventname = EventName; This.targetname = target. GetType ().            Name; EventInfo info = target. GetType ().            GetEvent (EventName); Eventhandletype = info.            Eventhandlertype; Delegate handler = delegate.createdelegate (Eventhandletype, this, this. GetType ().            GetMethod ("oneventfired")); Info.        addEventHandler (target, handler);            }///<summary>//Get Object references///</summary> public object Target { get {return wrapper. Target;        }}///<summary>//object name for display///</summary> public string TargetName        {get {return targetName;}            }///<summary>//Determine if the object is alive///</summary> public bool IsAlive { get {return wrapper. IsAlive;    }}///<summary>//Event name///</summary> public string EventName    {get {return eventName;}            }///<summary>///Event processing type///</summary> public type Eventhandletype {        get {return eventhandletype;}            } public virtual void Oneventfired (object sender, EventArgs e) {var handle = eventfired;        if (handle! = NULL) handle (this, sender, E); } public override string ToString () {return string.        Format ("[{0}-{1}]", TargetName, EventName); }    }}
    • subscribers, still using weak references to save the target object
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading;using System.threading.tasks;namespace tinyeventbroker{//<summary>///Subscribers///</summary> public Clas s eventsubscription {//<summary>///Weak Reference object wrapper///</summary> private readonl        Y WeakReference wrapper;        <summary>//Method name///</summary> private readonly string methodName;        <summary>///object name, only for display///</summary> private readonly string targetName;            Public Eventsubscription (Object target, String methodName) {this.wrapper = new WeakReference (target);            This.methodname = MethodName; TargetName = target. GetType ().        Name;            }///<summary>//Whether the object is alive///</summary> public bool IsAlive { get {return wrapper. IsAlive;   }        }     <summary>////Subscriber object Method name///</summary> public string MethodName {get {return me Thodname; }}///<summary>///Subscriber object with weak reference wrapper access///</summary> public object Target {get { Return wrapper. Target; }}////<summary>///Subscriber Object Explicit name///</summary> public string TargetName {get {ret Urn TargetName;            }} internal virtual void handleevent (eventpublication publication, object sender, EventArgs args) { Delegate handler = delegate.createdelegate (publication.            Eventhandletype, Target, methodName); Handler.        DynamicInvoke (sender, args); } public override string ToString () {return string.        Format ("[{0}-{1}]", TargetName, MethodName); }    }}
    • Eventscope, this thing is just a reserved property, later extended with
Preliminary test results

Reference

For the weak reference this thing, actually directly using the weak event mode, Microsoft has encapsulated the

Weak Event Patterns,weak event in C #

Conclusion

This is just a simple implementation of eventbroker, purely learning practiced hand, I think, if the follow-up I have sufficient time, or the work environment allows, I can achieve better, such as can be encapsulated in the internal multi-clock policy, exception handling policy, asynchronous event policy, processing concurrency, thread safety considerations and so on. What's more, it can be abstracted and extended to join the message middleware to implement distributed publishers and Subscribers, so it is more practical value. But writing code level and efficiency is limited, time and energy is limited, work is study is learning, only a article, chat table my enthusiasm and development, let code and life can continue!

SOURCE download

C # Programming Practice-eventbroker Simple implementation

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.