ASP. net mvc + EF framework + EasyUI permission management series (6)-EF context instance Management

Source: Internet
Author: User

Through the previous five blogs, we have already explained in detail the back-end architecture of the permission system. Then I mentioned in my previous blog that our back-end architecture will be changed, I am going to continue to improve our background during this period. By the way, I can review the previous design architecture. Now we will start today's blog series. I hope everyone can give me support, your support is my motivation. If you still feel that you can write it, please do not click it.

1. describe the implementation of the previous architecture

(1) When our project is here, it is necessary to describe the functions implemented by my current architecture. First, I will draw a picture, and then I will explain in detail the meanings of these files.

(2) Next we will explain the usage and functions of the Project class library for the entire project.

1) LYZJ. UserLimitMVC. UI. Portal Project, UI Layer, responsible for displaying project pages, pages implemented using EasyUI and MVC4.0.

2) The LYZJ. UserLimitMVC. Model class library is used to store the Model of the data table Entity. The Entity FrameWork Model is placed here. That is, the EF framework is used to operate databases.

3) The LYZJ. UserLimitMVC. Common class library is used to store some public information and classes. For example, Md5 encryption algorithm, file upload, format conversion, and so on.

4) LYZJ. userLimitMVC. the DAL class library is the implementation of the database access layer. Because we add, delete, modify, and query database operations, we encapsulate a basic interface for database operations, then, the objects in other database access layers only need to inherit the self-base interface to perform database operations. Here we also add a factory (warehouse ), use a simple factory to manage instance creation. In this way, we encapsulate the modes of instance creation into a simple factory. High Cohesion and low coupling are achieved.

5) LYZJ. userLimitMVC. the IDAL class library and database access interface layer are used to store the interface information of the database access layer. Because we operate on the database, we encapsulate a base interface, then let other object interfaces inherit from the base interfaces.

6) LYZJ. UserLimitMVC. BLL class library. This is our implementation of the business logic layer. It shares the same idea with the database access layer, but we implement abstraction of the database access layer.

7) The LYZJ. UserLimitMVC. IBLL class library and business logic interface layer are used to store business logic interfaces. The implementation idea is consistent with that of the database access layer.

(3) We have already used the interface-dependent programming and simple factory model. Here, we remind the blog that we should not stick to some design patterns when we are working on projects, only when these design patterns match our application scenarios, we are trying to use these design patterns. Generally, when we are writing a project, we are using some design patterns, but we don't know it. When we finish writing, we find that we have used some design pattern.

(4) We will continue to encapsulate the database access layer.

2. encapsulation of the database access layer

(1) Let's analyze the RepositoryFactory class under the LYZJ. UserLimitMVC. DAL class library. First, I post the code of the RepositoryFactory class and then explain it:


1 namespace LYZJ. UserLimitMVC. DAL
2
3 {
4
5 public static class RepositoryFactory
6
7 {
8
9 public static IUserInfoRepository UserInfoRepository
10
11 {
12
13 get {return new UserInfoRepository ();}
14
15}
16
17 public static IRoleRepository RoleRepository
18
19 {
20
21 get {return new RoleRepository ();}
22
23}
24
25}
26
27} (2) This RepositoryFactory class is operated by a simple factory. Here we use a simple factory to get all the warehousing instances (UserInfoRepository, RoleRepository ), in fact, from another perspective, this simple factory is a unified entrance to our database access layer. Why? Because we can get all the warehousing from this simple factory, and since we can get all the warehousing, we can operate all the tables, so this warehousing (RepositoryFactory) it is the unified entrance of our database access layer.

(3) Next we will convert this simple factory into another method. Based on the unique rule in the thread.

3. EFContextFactory, DbSession Summary

(1) first, we create a DbSession class under the LYZJ. UserLimitMVC. DAL class library. What does this DbSession do? First, let's assume that DB represents the database, and Session represents a Session.

(2) In ASP. the Session is also used when the request page is in. Session indicates the start of a Session. After all our requests are completed, the Session ends after the browser is closed, that is to say, a process in one of his requests is called a session,

(3) What does this DbSession mean? This means that we have a session with the database. When we send a request, we need to perform many interactions with the database, we call this whole process of interaction a session. The session is enabled when we operate the database. When the database operation ends and the request ends, the session for accessing the database ends.

(4) If we want to operate the database, we need to perform operations through this session. In DbSession, We can get all our warehouses, then we can add, query, modify, and delete all tables. After adding, deleting, querying, modifying, and modifying all the tables, you can submit the database at one time through DbSession because it is a session, therefore, all the changes in this session are submitted back to the database, and then batch commit is implemented.

4. DbSession a session with the database

(1) first, we need to understand the role of the DbSession class, which represents a session between the application and the database. from another perspective, it is also a unified entrance to the database access layer. (Abstraction of the entire database access layer ).

(2) then we will write the DbSession code, which contains detailed comments. You can see:


1 namespace LYZJ. UserLimitMVC. DAL
2
3 {
4
5 // a session that interacts with the database. It encapsulates all the attributes of the warehouse and obtains the attributes of the warehouse according to the DbSession.
6
7 public class DbSession // indicates a session between the application and the database, which is also the unified entrance to the database access layer.
8
9 {
10
11 public IDAL. IRoleRepository RoleRepository
12
13 {
14
15 get {return new RoleRepository ();}
16
17}
18
19
20
21 public IDAL. IUserInfoRepository UserInfoRepository
22
23 {
24
25 get {return new UserInfoRepository ();}
26
27}
28
29 // representative: changes to all entities in the painting of the current application and database. The updated database
30
31 public int SaveChanges ()
32
33 {
34
35 // call the SaveChanges method of the EF Context
36
37 return 0;
38
39}
40
41}
42
43} (3) according to the above Code comment, we can see that the SaveChanges method in the context is called. What about the SaveChanges method in the context? Next, let's take a look at the processing of our previous EF context.

5. EF context Processing

(1) first, find LYZJ. userLimitMVC. in the BaseRepository class under the DAL class library, we can see that we used new to implement it directly, so there will be many context instances in our entire project, and we have encountered many times, when we encounter many problems during programming, we usually need to think about whether we can solve this problem.

(2) how to manage EF context? It's easy, that is, to ensure that the thread is unique, so here we need to modify the BaseRepository class.

(3) What is the role of BaseRepository in warehousing? His role is to help us implement public methods for all sub-warehouses (add, delete, query, and modify). His responsibilities do not include how to manage context instances, therefore, we cannot place the unique code in the thread that controls the context instance in this position. This means that the responsibilities of each class must be unique. One aspect of object-oriented is that the responsibilities of classes must be single.

(4) let's take a look at the modified BaseRepository (warehouse). Here I only list a small part, because none of the following has changed.


1 namespace LYZJ. UserLimitMVC. DAL
2
3 {
4
5 /// <summary>
6
7 // implement the base class for database operations (add, delete, modify, and query)
8
9 /// </summary>
10
11 // <typeparam name = "T"> define a generic type and constrain it as a class </typeparam>
12
13 public class BaseRepository <T> where T: class
14
15 {
16
17 // create the context of the EF framework
18
19 // The EF context instance ensures that it is unique within the thread
20
21 // private DataModelContainer db = new DataModelContainer ();
22
23 //
24
25 private DbContext db = EFContextFactory. GetCurrentDbContext ();
26
27 // Add the database and reference the EF framework
28
29 public T AddEntity (T entity)
30
31 {
32
33 // EF4.0
34
35 // db. CreateObjectSet <T> (). AddObject (entity );
36
37 // EF5.0
38
39 db. Entry <T> (entity). State = EntityState. Added;
40
41 // The following statements are unified
42
43 db. SaveChanges ();
44
45 return entity;
46
47}
48
49}
50
51} (5) So how do we control the context instance and require it to be unique within the thread? At this time, we can't set it in the BaseRepository (warehouse). At this time, we thought of encapsulation, we want to encapsulate an instance that controls the context and requires it to be the only code in the thread into a public class. What should we do at this time? Please refer to the following practices

(6) Now we can see that the above Code cannot be implemented directly by new (// private DataModelContainer db = new DataModelContainer ();). How can we get this instance? The key point is that the instance to be retrieved here must be public and can help us manage the uniqueness in the thread. At this time, we can think that we can implement this instance through the factory, then we create an EFContextFactory here. In this factory, the GetCurrentDbContext () method is provided to return the instance (private DbContext db = EFContextFactory. getCurrentDbContext ();). At this time, we need to create the above class.

6. EFContextFactory

(1) At this time, we are in LYZJ. userLimitMVC. the DAL class library then creates an EFContextFactory class, which contains the GetCurrentDbContext method. Next I will explain the implementation of these codes. The code for implementing this method is:


1 namespace LYZJ. UserLimitMVC. DAL
2
3 {
4
5 public class EFContextFactory
6
7 {
8
9 // help us return the database context in the current thread. If there is no context in the current thread, create a context and ensure
10
11 // The online Q & A instance is unique within the thread
12
13 public static DbContext GetCurrentDbContext ()
14
15 {
16
17 // CallContext: it is the only dedicated data slot within the thread (one memory space)
18
19 // pass DbContext to obtain the instance information, and perform forced conversion here.
20
21 DbContext dbContext = CallContext. GetData ("DbContext") as DbContext;
22
23 if (dbContext = null) // The thread does not have this context in the data slot
24
25 {
26
27 dbContext = new DataModelContainer (); // if no context exists, create an EF Context
28
29 // create one and put it in the data slot
30
31 CallContext. SetData ("DbContext", dbContext );
32
33}
34
35 return dbContext;
36
37}
38
39}
40
41} (2) First, we can see that DbContext is returned when defining the method. Here, we need to note that we use DbContext in EF5.0, but we use ObjectContext in EF4.0, so what does DbContext do? Its function is to help us return the database context in the current thread. If there is no context in the current thread, we will create one directly and ensure that the context instance is unique within the thread.

(3) What is the CallContext class used here? The above mentioned in MSDN is as follows:

1) Data address: http://msdn.microsoft.com/zh-cn/library/system.runtime.remoting.messaging.callcontext (VS.80). aspx

2) Then we can find the note: CallContext is a dedicated set object similar to the local storage area of the thread for method calling, and provides a data slot (data storage area) that is unique to each logic execution thread ), the data slot is not shared between call contexts on other logic threads. When CallContext is propagated back and forth along the Execution Code path and each object in the path is checked, you can add the objects to it.

3) when a remote method is called for an object in another AppDomain, The CallContext class will generate a LogicalCallContext instance that is propagated together with the remote call, only the external AppDomain that exposes the ILogicalThreadAffinatice interface and objects stored in CallContext are propagated in LogicalCallContext. Objects of this interface cannot be transmitted together with remote method calls in the LogicalCallContext instance.

(4) There are two important static methods in CallContext

1) void SetData (string name, object data), which is used to store data in the collection.

2) object GetData (string name) indicates that the data is retrieved, and a Key is passed to retrieve the corresponding value.

(5) At this time, Let's explain the execution process. When the thread first comes over, first call the code of this method (GetCurrentDbContext) and check whether this thread exists in the data slot, of course, this is definitely not the first time. At this time, we create one and store it in dbContext. At this time, we will directly return the new object. When the second request comes, when the data is obtained in the data slot, the information is returned directly without judgment. Then, the information can be retrieved directly. Note: It is only inside the current thread. This ensures that the context in the thread is unique.

  

 

Related Article

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.