[MSH] a lightweight but practical framework of the WCF module service + the MSH of the WCF module service hosting program [Opening]

Source: Internet
Author: User

This article is about a lightweight but practical module service framework and service hosting program MSH Based on WCF, including analysis of several common application scenarios, as shown in the following table:

I. Introduction and explanation of the WCF module framework

II. Introduction and explanation of module service host (MSH)

Iii. Analysis of Common application scenarios

Iv. Enhancement of later Functions

V. Open-source plan

 

Download msh1.0 (for. Net 3.5)

 

Download the simplest mshdemo (for vs2010 &. Net 3.5)

 

 

This is only the beginning. In the future, articles about development module instances and application-related instances will be published.

 

I. Introduction and explanation of the WCF module framework

Service-Oriented Architecture-SOA is becoming more and more important in the IT field. Windows Communication Foundation (WCF) is a service-oriented architecture of Microsoft. from a functional perspective, WCF can be viewed as asmx ,. the Union of net remoting, Enterprise Service, WSE, MSMQ and other technologies. If you are not familiar with WCF, go to the encyclopedia to view the information.

So what is the WCF module framework? It is a lightweight but practical framework (in the namespace kudysharp. Frameworks. wcfmoduleframework of kudysharp) that I wrote for my current company ). The current version supports the following main functions:

1. Supports the routing and transit service of WCF;

2. Supports custom channel context. The channel context allows you to transmit additional data when calling the WCF Service, making interaction between the client and the server more flexible;

3. supports dynamic loading and unloading of module services. With this feature, you can quickly deploy and use your WCF Service;

4. Support token verification when module services are hosted and called;

5. Support custom channel security verification for each module and refine each service method;

6. support different channel contexts for different module services.

 

See the following simple request processing process diagram of the client calling module host (MSH is the WCF module service hosting program described in the next section ):

 

  

The figure indicates that the Framework hosts n module services, and each module service has one or more available services. When a client sends a request to a module service, the framework first verifies the channel context used by the service of this module. If the channel context exists, it verifies the token of the module. If the token is valid, it executes custom channel verification methods for some module services, if the verification succeeds, the service to be called is returned to the client. What happens when routing is enabled? For example, if the client needs to call services on host B through host a, host a simply forwards requests to host B and then host B completes the request process described above, then, the service is returned to host a and then to the client.

 

The following describes the main members of the WCF module framework (only list the members You Want To Know when developing the module, In the kudysharp namespace kudysharp. Frameworks. wcfmoduleframework ).

 

  1. Module host (base) Class modulehost, which is the base class to be inherited from the custom module host.

Routingenabled: Indicates whether to enable a route. If no routing service is required, rewrite it and return false. The default value is enabled.

Tokenresolver: token processor. The default value is nulltokenresolver. Token verification is not performed.Strongly recommendedImplement your own token processor, implement the itokenresolver interface, or inherit the tokenresolverbase <tresolver> class.

Portconfigmanager: Port Configuration Manager. The default value is xmlportconfigmanager, Which is configured in XML format. If necessary, you can implement your own Port Configuration Manager and the iportconfigmanager interface.

Getchannelcontexttypesforroutingservice (): gets the channel context type to provide the routing service. This method is designed to provide the routing service only on an independent server. By default, null is returned, override this method to return your own channel context type, for example, return new list <type> {typeof (mychannelcontext )};;In addition, the channel context used by the module base class mentioned below does not need to be returned here, because if routing is enabled, the Framework automatically opens the routing service for the channel context used by all modules.

// Module host (base) class public class modulehost: imodulehost {/* attribute * // whether public bool isloaded {Get;} has been loaded ;} // whether to enable the public virtual bool routingenabled {Get;} // module storage directory Public Virtual string moduledirectory {Get;} // public idictionary in the working module list <string, workingmodule> workingmodules {Get;} // token processor. The default value is nulltokenresolver Public Virtual itokenresolver tokenresolver {Get;} // Port Configuration Manager. The default value is: xmlportconfigmanager Public Virtual iportconfigmanager portconfigmanager {Get;}/* main method member * // loads public void load (); // loads the core implementation protected virtual void loadcore (); // uninstall public void unload (); // uninstall the core implementation protected virtual void unloadcore (); // obtain the channel context Type Public Virtual ilist <type> getchannelcontexttypesforroutingservice ();/* main event * // trigger public event eventhandler loaded after host loading; // public event eventhandler loading is triggered when the host is being loaded; // public event eventhandler unloaded is triggered after the host is uninstalled; // public event eventhandler unloading is triggered when the host is being uninstalled; // trigger the public event eventhandler <moduleloadfailedeventargs> moduleloadfailed when the module fails to load; // trigger the public event eventhandler <modulestatechangedeventargs> modulestatechanged; // trigger public event eventhandler <workingmoduleaddedeventargs> workingmoduleadded after the work module is added; // trigger public event eventhandler <strong> workingmoduleremoved after the work module is removed; /* default method for executing the preceding events */protected virtual void onloaded (Object sender, eventargs E); protected virtual void onloading (Object sender, eventargs E ); protected virtual void onunloaded (Object sender, eventargs E); protected virtual void onunloading (Object sender, eventargs E); protected virtual void onmoduleloadfailed (Object sender, subject e ); protected virtual void onmodulestatechanged (Object sender, Volume E); protected virtual void onworkingmoduleadded (Object sender, Volume E); protected virtual void onworkingmoduleremoved (Object sender, Volume E );}

 

2. The token processor interface itokenresolver, which is the interface required to implement the custom token processor. It can also inherit the tokenresolverbase <tresolver> base class.

// Token processor interface public interface itokenresolver {// generate the module token string generatetoken (string servicename); // verify the module token bool verifytoken (string servicename, string tokentoverify );}

 

3. Port Configuration Manager interface iportconfigmanager, which is the interface to be implemented by the custom Port Configuration Manager. You can also inherit the XML Port Configuration Manager xmlportconfigmanager.

// Port Configuration Manager interface public interface iportconfigmanager {// obtain the service port ilist <int> serviceports {Get;} // configure namevaluecollection getconfig (INT port) based on port retrieval ); // Save the configuration void saveconfig (INT port, namevaluecollection configs) based on the port; // determine whether the configuration item is valid bool isconfigitemvalid (string name, string value, out string errormessage );}

 

// XML Port Configuration Manager (base) class public class xmlportconfigmanager: iportconfigmanager {// obtain the configuration directory Public Virtual string configdirectory {Get ;} // obtain the service Port Public ilist <int> serviceports {Get;} // obtain and configure public namevaluecollection getconfig (INT port) based on the port ); // Save the configuration public void saveconfig (INT port, namevaluecollection configs) based on the port; // determine whether the configuration item is legal public bool isconfigitemvalid (string name, string value, out string errormessage );}

 

Understand the above3You can develop your own module host. Let's continue to look at the members You Need To Know when developing your module service:

 

4. Channel context base class channelcontextbase <tcontext> is the base class to be inherited to implement custom channel context. You should be careful to see that this class inherits the base class channelcontextbase, channelcontextbase is only a transitional class that implements framework functions. Therefore, you only need to care about channelcontextbase <tcontext>. In addition, channel context and attributes must be serializable, do not forget to add the serializable feature.

Contextheaderlocalname/contextheadernamespace: We recommend that you return the localname and namespace of your defined header information.

Returnmessage: return information, which is generally the information returned from the server to the client. When an error occurs on the server, the error information is saved in this attribute for use by the client.

This [String key]: obtains or sets context data through the key. This is used to help you use mychannelcontext when you do not define specific attributes when inheriting the context base class. current ["mykey"] to set or access additional communication data.

International time-related and server-related members will not be explained much, and the subsequent instance articles will explain one by one.

// Channel context base class [serializable] public abstract class channelcontextbase <tcontext>: channelcontextbase where tcontext: channelcontextbase <tcontext>, new () {/* header information * // localname protected internal virtual string contextheaderlocalname {Get ;}// namespace protected internal virtual string contextheadernamespace {Get ;} /* basic attribute * // obtain the current channel context instance public static tcontext current {Get; set;} // return information (information returned from the server to the client) public String returnmessage {Get; set;} // get or set the context data public object this [String key] {Get; set ;} /* International time related * // time zone public timezoneinfo timezone {Get; set;} // convert the local time to the UTC time public datetime converttimetoutc (datetime) according to the timezone attribute ); // convert the local time from UTC to public datetime converttimefromutc (datetime) based on the timezone attribute;/* server-side (invalid client call) * /// obtain the current service Port Public int getserviceport (); // obtain the service name of the current module Public String getservicename (); // obtain the configuration public namevaluecollection getconfig () for the current service port; // obtain the original Client IP address of the current request public string getremoteendpointaddress (); // obtain the Client IP address of the current request (whether or not the original client can be specified) Public String getremoteendpointaddress (bool original );}

 

5. Module Base Class modulebase <tcontext, tcontract, tservice>, which is the base class to be inherited by the Development custom module. tcontext is the channel context used by this module, and tcontract is the WCF interface constraint, tservice is a service class that implements tcontract interface constraints.

Token: gets the token. By default, servicename is returned. For details, return the token generated by the tokenresolver Based on servicename in the module host.

Servicename: gets the service name. By default, the class name of this module class is returned. We recommend that you return a meaningful name (for example:Myservice), Note that the service names of each module on the same module host must be unique, and the token above must also be unique.

Servicedescription: gets the service description. By default, an empty string is returned. This attribute is optional.

Channelverifier: gets Channel validators. The default value is nullchannelverifier, which implements custom channel validators,Strongly recommendedImplement your own channel validators and the interface ichannelverifier.

Createnettcpbinding (): gets the nettcpbinding used to open the service. To use a custom nettcpbinding instance, override this method.

// Module Base class public abstract class modulebase <tcontext, tcontract, tservice>: imodule where tcontext: channelcontextbase <tcontext>, new () Where tservice: tcontract, new () {/* Basic Attributes * // obtain the token public virtual string token {Get;} // obtain the service name public virtual string servicename {Get ;} // obtain the service description Public Virtual string servicedescription {Get;} // obtain the module status public modulestate state {Get;} // obtain the channel validators. The default value is: nullchannelverifier Public Virtual ichannelverifier channelverifier {Get;}/* Basic Method * // open the module public bool open (); // close the module public bool close (); // Public Virtual void onload () after the module is framework; // Public Virtual void onUnload () after the module is uninstalled (); // obtain the nettcpbinding Public Virtual nettcpbinding createnettcpbinding () used to open the service; // obtain the endpointbehavior Public Virtual ilist <iendpointbehavior> createendpointbehaviors () to be added when the service is opened (); /* main event * // public event eventhandler opening is triggered when the event is being enabled; // public event eventhandler opened is triggered when the event is enabled; // public event eventhandler closing is triggered when the event is being disabled; // public event eventhandler closed is triggered when it is disabled; // public event eventhandler faulted is triggered when it fails;/* default method for executing the above main events */protected virtual void onopening (Object sender, eventargs E); protected virtual void onopened (Object sender, eventargs E); protected virtual void onclosing (Object sender, eventargs E); protected virtual void onclosed (Object sender, eventargs E ); protected virtual void onfaulted (Object sender, eventargs E );}

 

6. The channel validators interface ichannelverifier is the interface to be implemented by the custom channel validators. You can also inherit the channel validators interface base class channelverifierbase <tverifier>.

// Channel validators interface public interface ichannelverifier {// verification channel verifychannelresult verifychannel (Object contextstate, message );}

 

Understand the above3You can develop your own module services. Next we will continue to look at the members You Need To Know when calling your module services:

 

7. Module client class moduleclient, which is the helper class for the client to call the module service. It is easy to use and will not be said much.Tmodule is the call module, and tchannel is the WCF interface constraint of tcontract in tmodule, which facilitates the use of interface methods in action.

// Module client class public static class moduleclient {// create channel: no return value. Use nettcpbinding public static void createchannel created by tmodule <tmodule, tchannel> (string server, int port, action <tchannel> action, Params string [] routingservers) Where tmodule: imodule, new (); // create channel: return value, nettcpbinding public static tresult createchannel created using tmodule <tmodule, tchannel, tresult> (string server, int port, func <tchannel, tresult> action, Params string [] routingservers) Where tmodule: imodule, new (); // create channel: no return value. Use your own nettcpbinding. If it is null, use nettcpbinding public static void createchannel created by tmodule <tmodule, tchannel> (string server, int port, nettcpbinding binding, Action <tchannel> action, Params string [] routingservers) Where tmodule: imodule, new (); // create a channel: if the value is null, use the self-defined nettcpbinding. If the value is null, use the nettcpbinding public static tresult createchannel created by tmodule <tmodule, tchannel, tresult> (string server, int port, nettcpbinding binding, func <tchannel, tresult> action, Params string [] routingservers) Where tmodule: imodule, new ();}

 

How to use it?

ModuleClient.CreateChannel<TModule, TChannel>(server_A, port, proxy =>{ //use service of server_A //proxy.hellowork();});ModuleClient.CreateChannel<TModule, TChannel>(server_A, port, proxy =>{ //use service of server_D //proxy.hellowork();}, server_B, server_C, server_D);

 

 

If you carefully read all the above members and believe that you already know how to use this framework, we will continue to look at the next section.

 

II. Introduction and explanation of module service hosting (MSH)

The framework mentioned above has been implemented, so we always need a program to manage the module services we write? To save your time and make it easier to use this framework, I also wrote a module service hosting master program based on the WCF module framework, named: module service hosting (MSH ).

Module service hosting (MSH) is a WCF Service Module hosting program. It provides common functions to manage custom module services, you can quickly develop and deploy your own WCF Service to facilitate communication between applications.

 

MSH main program related files:

  

For more information about directories, seeDescriptionFolder.

 

The following describes the main interfaces of MSH:

1. Main Interface

  

2. Configuration Management

  

3. Token Generation

  

4. Run the check.

  

  

The above is the same interface, because the Administrator permission is required to add a window task. When MSH is run as an administrator, the first interface is displayed; otherwise, the first interface is displayed, you must enter the user name and password for execution.

 

 Iii. Analysis of Common application scenarios

The following is a simple example of a scenario. In subsequent articles, we will provide various examples and source code for your reference.

Application Scenario 1:

  Example 1 ):A company has multiple servers to maintain and monitor abnormal information. In this case, you can deploy MSH on each server and then use server A as the MSH client, A web system is used to call the module service on MSH. MSH configuration only allows server a to call the service. The specific service depends on the maintenance and monitoring.

  Example 2 ):A game developed by a game company is divided into N game zones. The data in the first zone is separated independently. a gm system needs to be developed to manage the business data of all game zones, you can deploy MSH on each server, and then use GM server A as the MSH client. Different servers can call the module Service to manage business data, the specific data depends on the game business. (I used this solution by gaming companies before)

 

Application Scenario 2:

 

  Example 1 ):A company needs to use multiple servers to implement distributed caching and provide data to system A. In this case, MSH can be deployed on each server, and system a acts as the MSH client, when the module service on MSH is called, MSH configuration only allows the server on which system A is located to call the service. The specific service is the read and write of cached data, which is directly used. the cache class in. Net can be implemented, with emphasis onNode PositioningDetermine the server service to be called based on the specific policies and algorithms. (This is just a solution example. Generally, distributed cache is used to the memcached solution. At least I know that many companies are like this)

Example 2 ):A company needs a service to implement a load balancing cluster and provide services to system A. In this case, MSH can be deployed on each server, and system a acts as the MSH client to call the module service on MSH, MSH configuration only allows the server of system A to call services,Node PositioningAs in the previous example, the specific policies and algorithms are used to determine the server service to be called.

 

Application Scenario 3:

 

 

Application Scenario 3AndApplication Scenario 2It's almost the same. It's just about making a server public to the outside, providing the routing and transit service. Actually, it's about N servers on the internal LAN.

 

 Iv. Enhancement of later Functions

This new version of the WCF module framework can meet basic functional requirements. In the future, we will consider service workflows, automatic updates, and more flexible scalability, you are also welcomed to provide some valuable comments.

 

V. Open-source plan

As one of our key class libraries, kudysharp does not disclose source code. Please do not ask for it. The MSH program will publish the MSH source code after the function is improved later. The specific time is not fixed. If you need the source code of MSH, use your company email to send an email to kudychen # gmail.com.

 

Download msh1.0

Download the simplest mshdemo

 

This software can be used by individuals or enterprises for free. If you like MSH, don't forget to mention it :)

 

Disclaimer:

1. This software and the attached documents are provided in the form of no clear or implied compensation or guarantee.
2. If you use the software voluntarily, you must understand the risks of using the software. We are not liable for any problems arising from the use of the software.

 

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.