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 understand the .NET context-oriented Architecture pattern

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

In this issue, the editor will bring you about how to understand the .NET context-oriented architecture model. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

1. Context Overview

Context: it is actually a logical business and functional area. It can be effectively managed in this logical area, which can be regarded as a kind of institutional constraint, and it can also be understood as a certain range of data sharing.

In fact, the concept of context can be seen everywhere in many application frameworks, including the design of .NET itself based on this idea. The instantiated object exists by default in the default context in the system, and we can build our own context to manage the object reasonably at run time.

What is more classic in the ASP.NET framework is the HttpContext context object. All runtime objects are logically assigned to the HttpContext context, for example, we can use Request, Response and other objects to access the life cycle data processed by HTTP.

In Remoting, cross-AppDomin access is also based on context, and the requested message is serialized to the call after being tunneled. Copyright Wang Qingpei. Please give your signature when reproduced.

Behind these powerful application frameworks, there are always elusive design secrets, and many design principles, design patterns and rich practical experience will be the cornerstone of the stable operation of the framework. Context is a relatively perfect logical scope design pattern. [copyright Wang Qingpei, please give your signature for reprint]

So let's get a taste of the mystery of context.

two。 General application of context

The design idea of context is absolutely wonderful, and in many places, once the context is abstracted, it can solve a lot of problems. For example, in Remoting, we can dynamically add many extensions to the context to forcibly manage all the objects in the context. For example, if we call a method, we need to conduct a security check, and we can write a security authentication plug-in that meets the needs of our current project and dynamically inject it into the context manager area, where the design advantage of the context is reflected.

In Web programming, because it is very different from Winfrom programming, it is necessary to use the same group of objects in N clients at the same time, while in Winfrom, it basically belongs to single thread, of course, you can manually turn on multi-thread parallel operation. For ASP.NET, whenever a new request is processed, the framework automatically starts a new thread to handle the current call, and then requires a separate context data environment relative to the previous operation, rather than that all threads on the same server are shared. Copyright Wang Qingpei. Please give your signature when reproduced.

Then we need to put the relevant data processed by the current HTTP into a logical context for management and data sharing.

With so many advantages, it seems necessary for us to try this design pattern. So where can we use our context in terms of the current system development framework? I think the top priority is to manage the context of all single-line objects in the hierarchical architecture. [copyright Wang Qingpei, please give your signature for reprint]

A typical three-tier architecture:

In the general three-tier architecture development process, our invocation relationship is basically like this, using the context design pattern, we can reasonably manage the objects we would have encouraged. In the figure above, the User object line will belong to the User context, and the Order object line will belong to the Order context. Without interfering with each other, you can share data in this logical context, set security policies to invoke, design logging methods, and even calculate the performance of each method.

The calling code of BLL:

View Code / * author: in-depth training * blog: http://wangqingpei557.blog.51cto.com/ * * / using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace ConsoleApplication1.BLL {[ContextModule.ContextEveningBound (IsEvening = true)] public class BLL_Order: ContextModule.ContextModuleBaseObject {DAL.DAL_Order dal_order = new DAL.DAL_Order () [ContextModule.ContextExceptionHandler (OperationSort = 1)] public Model.Model_Order InsertOrderSingle (Model.Model_Order ordermodel) {return ContextModule.ContextAction.PostMethod (dal_order, dal_order.GetMethodInfo ("InsertOrderSingle"), ordermodel) } [ContextModule.ContextExceptionHandler (OperationSort = 1)] public void SendOrder (Model.Model_Order ordermodel) {ContextModule.ContextAction.PostMethod (dal_order, dal_order.GetMethodInfo ("SendOrder"), ordermodel);}}

The execution code of DAL:

View Code / * author: in-depth training * blog: http://wangqingpei557.blog.51cto.com/ * / using System; using System.Collections.Generic; using System.Text Namespace ConsoleApplication1.DAL {[ContextModule.ContextEveningBound (IsEvening = true)] public class DAL_Order: ContextModule.ContextModuleBaseObject {[ContextModule.ContextLogHandler (OperationSort = 1)] [ContextModule.ContextSecurityHanlder (OperationSort = 2)] public Model.Model_Order InsertOrderSingle (Model.Model_Order ordermodel) {return new Model.Model_Order () {OrderGuid = Guid.NewGuid (), OrderTime = DateTime.Now} } [ContextModule.ContextLogHandler (OperationSort = 1)] public void SendOrder (Model.Model_Order ordermodel) {Console.WriteLine ("order sent successfully!") ;}

The above code is the execution process that I simulate a context.

3. Context sharing area

There should be a shared data storage area in each separate context for multiple context objects to access. This convenience is mostly used in the expansion method when the project is tense to modify the requirements or to add new business. BLL call code:

View Code [ContextModule.ContextExceptionHandler (OperationSort = 1)] public void UpdateOrderSingle () {Model.Model_Order ordermodel = new Model.Model_Order () {OrderGuid = Guid.NewGuid (), OrderTime = DateTime.Now}; / / put into context shared object pool ContextModule.ContextRuntime.CurrentContextRuntime.SetValue ("updateorder", ordermodel) ContextModule.ContextAction.PostMethod (dal_order, dal_order.GetMethodInfo ("UpdateOrderSingle"), null);}

DAL executes the code:

[ContextModule.ContextLogHandler (OperationSort = 1)] public void UpdateOrderSingle () {Model.Model_Order ordermodel = ContextModule.ContextRuntime.CurrentContextRuntime.GetValue ("updateorder") as Model.Model_Order;}

4. Contextual runtime environment

The construction of the context runtime environment needs to take into account that the runtime is a shared context object. All objects that are included in context management need to be shared or controlled by the context runtime.

Contextual construction:

View Code / * author: in-depth training * blog: http://wangqingpei557.blog.51cto.com/ * * / using System; using System.Collections.Generic; using System.Text; namespace ContextModule {/ context runtime environment. / / context logic runtime environment, the functions in the environment can be attached. / public class ContextRuntime: IDisposable {# region IDisposable member void IDisposable.Dispose () {_ currentContextRuntime = null;} # endregion protected ContextRuntime () {} private DateTime _ initTime = DateTime.Now / get the time when the context was created at runtime / public virtual DateTime InitTime {get {return _ initTime;}} private Dictionary _ runTimeResource = new Dictionary (); private ContextFilterHandlerMap _ filterMap = new ContextFilterHandlerMap () / get the method and class filter mapping table in the context / public ContextFilterHandlerMap FilterMap {get {return _ filterMap;}} private Guid _ initPrimaryKey = Guid.NewGuid () / get the unique identity of the runtime creation context / public virtual Guid InitPrimaryKey {get {return _ initPrimaryKey }} / get data in the context sharing area / data Key / object data object public virtual object GetValue (object key) {return _ runTimeResource [key] } / set the data in the context sharing area / data Key / the data object public virtual void SetValue (object key, object value) {_ runTimeResource{ _ runTimeResource] = value to be set } [ThreadStatic] private static ContextRuntime _ currentContextRuntime; / get the current context runtime object. / public static ContextRuntime CurrentContextRuntime {get {return _ currentContextRuntime;}} / start runtime context / ContextRuntime public static ContextRuntime BeginContextRuntime () {/ / you can configure the parameters of the context runtime environment through the configuration file. This is just a simple simulation. _ currentContextRuntime = new ContextRuntime (); return _ currentContextRuntime;}

For the entry build of the context:

Using (ContextModule.ContextRuntime.BeginContextRuntime ()) {}

We start the context life cycle in the way of Using.

5. Contextual active object

The binding of the context object needs to be delayed and the context cannot be created when the object is built.

Use late binding to dynamically cut into the context of the execution.

Calling code, context entry:

View Code / * author: in-depth training * blog: http://wangqingpei557.blog.51cto.com/ * / using System; using System.Collections.Generic; using System.Text; using System.Data; using ConsoleApplication1.BLL; using ConsoleApplication1.Model Namespace ConsoleApplication1 {public class Program {public static void Main (string [] args) {BLL.BLL_Order order = new BLL.BLL_Order (); using (ContextModule.ContextRuntime.BeginContextRuntime ()) {Model.Model_Order ordermodel = new Model_Order () {OrderGuid = Guid.NewGuid (), OrderTime = DateTime.Now} Model.Model_Order resultmodel = ContextModule.ContextAction.PostMethod (order, order.GetMethodInfo ("InsertOrderSingle"), ordermodel); ContextModule.ContextAction.PostMethod (order, order.GetMethodInfo ("SendOrder"), ordermodel);}}

6. Application of context in hierarchical Architecture

With the core prototype of the context, we can extend it to the hierarchical architecture, which is actually necessary for the use of the hierarchical architecture. General large business systems are mixed usage patterns, such as Cmax S, Bhand S, Mobile terminals and so on.

After joining the Service layer, BLL and DAL will be located after the service, and the calls from the client will need to go through a series of authentication and permission grant. With WCF, the development of SOA-oriented architecture becomes relatively easy, perfect for security, performance, load, and so on, so in most cases we rarely need to control the execution and operation of BLL and DAL.

Then when there is no use of WCF to build a distributed system or there is no distributed requirement is a direct call, such as the general development of WEB, from UI to BLL to DAL. Or ordinary Winfrom projects, console projects belong to the use of the intranet, you may need to control the execution of the code.

Let me show you a concrete example to see how it works.

I use the program of the console as the demonstration project type, and I also use a simple three-tier architecture.

This couldn't be simpler. In order to demonstrate as simple as possible, the key is to highlight the point.

Demand:

Add a method to insert an Order entity object into the DAL object:

View Code / * author: in-depth training * blog: http://wangqingpei557.blog.51cto.com/ * / using System; using System.Collections.Generic; using System.Text Namespace ConsoleApplication1.DAL {[ContextModule.ContextEveningBound (IsEvening = true)] public class DAL_Order: ContextModule.ContextModuleBaseObject {[ContextModule.ContextLogHandler (OperationSort = 1)] [ContextModule.ContextSecurityHanlder (OperationSort = 2)] public Model.Model_Order InsertOrderSingle (Model.Model_Order ordermodel) {return new Model.Model_Order () {OrderGuid = Guid.NewGuid (), OrderTime = DateTime.Now} }}}

On top of this class is a feature, ContextEveningBound, that indicates that the current object belongs to an object that is later bound to the context. At the same time, this class also inherits from a ContextModuleBaseObject generic class, and its main function is to bind the object to the context for management.

There are two features on the method InsertOrderSingle, ContextLogHandler is used to record the execution log of the method, and ContextSecurityHanlder is used to force administrator authentication during the execution of the method.

BLL object code:

View Code / * author: in-depth training * blog: http://wangqingpei557.blog.51cto.com/ * * / using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace ConsoleApplication1.BLL {[ContextModule.ContextEveningBound (IsEvening = true)] public class BLL_Order: ContextModule.ContextModuleBaseObject {DAL.DAL_Order dal_order = new DAL.DAL_Order () [ContextModule.ContextExceptionHandler (OperationSort = 1)] public Model.Model_Order InsertOrderSingle (Model.Model_Order ordermodel) {return ContextModule.ContextAction.PostMethod (dal_order, dal_order.GetMethodInfo ("InsertOrderSingle"), ordermodel);}}

In the BLL object, there is an instance object that calls the DAL object method. In order to demonstrate the simple dependency injection design without adding a layer here, it is called directly. In the body of the BLL method, there is an interface dedicated to calling the method in context, which is constrained so that the framework can cut into the execution of the method before it is executed. I will explain the specific design principles in detail in the next article.

There is a ContextExceptionHandler feature above the method, which is designed to safely call the method of the DAL object and to humanize the error message in the case of an exception. In this way, we don't need to write code that catches exceptions frequently, and it doesn't look good, we want the code to be clean and beautiful.

UI call:

View Code / * author: in-depth training * blog: http://wangqingpei557.blog.51cto.com/ * / using System; using System.Collections.Generic; using System.Text; using System.Data; using ConsoleApplication1.BLL; using ConsoleApplication1.Model Namespace ConsoleApplication1 {public class Program {public static void Main (string [] args) {BLL.BLL_Order order = new BLL.BLL_Order () / / Open the context using (ContextModule.ContextRuntime.BeginContextRuntime ()) {Model.Model_Order ordermodel = new Model_Order () {OrderGuid = Guid.NewGuid (), OrderTime = DateTime.Now} Model.Model_Order resultmodel = ContextModule.ContextAction.PostMethod (order, order.GetMethodInfo ("InsertOrderSingle"), ordermodel);}}

Execution effect:

The log is recorded first, and then we are asked to enter user credentials before we can continue with the following method.

I type YES to continue with the insert method. We can control the method by simply implementing the management interface of the context.

Summary: this article only introduces the functions, principles and advantages of context.

This is how to understand the .NET context-oriented architecture model shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

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