MVC practical Architecture Design (II) -- use MEF practical IOC (dependency inversion)

Source: Internet
Author: User
Tags svn client
10. Directory

I. Preface

Ii. Advantages of MEF

Iii. Use of MEF in desktop programs

4. Use MEF in MVC

V. Source Code Retrieval

Vi. Series navigation

I. Preface

In the previous article, the basic project structure has been set up, but there is a problem: Although interfaces are used for isolation between layers, but when interfaces are instantiated, the interface implementation class dependency is also introduced. For example:

  Interface-Oriented ProgrammingThe Controller should only rely on the site service layer interface, rather than the specific implementation. Otherwise, it violates the original intention of setting interfaces between layers.

In addition, if the upper layer only depends on the lower layer interface, you can use Moq, Fakes, and other Mock tools to simulate interface implementation as needed during unit testing, you can flexibly control the return values of interfaces to test various situations. If you rely on specific implementations, the project's testability will be greatly reduced, making it difficult to conduct automated unit tests.

Instead of depending on the specific implementation, you cannot use the common T = new t () method to obtain a class instance. You need to use the IOC container to perform object lifecycle, dependency and so on.

Ii. Advantages of MEF

. There are many IOC containers available in. net, such as CastleWindsor, Unity, Autofac, ObjectBuilder, StructureMap, and Spring.. Net. These third-party tools vary, but their functions are basically the same. Most of them need to pair interfaces and implementations in advance (through code or configuration files ), then, the system automatically or manually obtains the instance of the corresponding implementation class through the interface, and the Object Instantiation is automatically completed by the IOC container.

What are the advantages of MEF over the above IOC containers? The reasons for my recommendation are as follows:

  1. . Net4.0 comes with: the MEF function can be directly referenced in the System. ComponentModel. Composition. dll assembly without installing third-party components.
  2. 0 configuration: MEF does not need to use configuration files or code to pair interfaces and implementations one by one. You only need to use a few Attribute features to automatically complete source and target pairing.
  3. Automation: the system automatically traverses the program directory or the dll under the specified folder during initialization, and performs automatic matching based on the interface in the program set and the specific Attribute features of the class.
Iii. Use of MEF in desktop programs

In the desktop program, you need to complete the directory matching of the two parts. One is the matching in the dll, the other is the matching in the exe assembly, and the two directory classes DirectoryCatalog and AssemblyCatalog are used respectively. The two directory classes must be added to the AggregateCatalog Directory class to participate in the initialization of CompositionContainer.

In the implementation class of the service provider, useExportAttributeMark the interface to match, as shown in. In the service caller, useImportAttributeAs shown in.

Because the call method is a static method, the instance of the Program class still needs to be manually obtained from the component container, and then try to log on:

In the output result, the AccountContract API does not assign values. However, it can output information about its implementation classes and can be called successfully upon Logon:

Iv. Use of MEF in MVC

In MVC projects, IOC components provide registration points to MVC through the SetResolver (IDependencyResolver resolver) method in the DependencyResolver class. Therefore, we only need to implement the MEF implementation class of the IDependencyResolver interface, you can complete the registration of MEF in MVC.

In addition, considering the stateless nature of Web applications, that is, each access is performed independently, the object instances generated by IOC components must also be unique. Otherwise, operations by different users may be serialized, mutual interference. Here, we use HttpContext. current. the Items set is used to store instances of the CompositionContainer combination container, so that each user's data remains independent and the same object instance is used in the same Http request of the same user. In addition, you may need to manually obtain the instances in the combined container and cache the combined container to the Application in the current context.

The implementation code of MefDependencySolver is as follows:

1 /// <summary> 2 // MEF dependency parsing class 3 /// </summary> 4 public class MefDependencySolver: IDependencyResolver 5 {6 private readonly ComposablePartCatalog _ catalog; 7 private const string HttpContextKey = "MefContainerKey"; 8 9 public MefDependencySolver (ComposablePartCatalog catalog) 10 {11 _ catalog = catalog; 12} 13 14 public CompositionContainer Container15 {16 get17 {18 if (! HttpContext. current. items. contains (HttpContextKey) 19 {20 HttpContext. current. items. add (HttpContextKey, new CompositionContainer (_ catalog); 21} 22 CompositionContainer container = (CompositionContainer) HttpContext. current. items [HttpContextKey]; 23 HttpContext. current. application ["Container"] = container; 24 return container; 25} 26} 27 28 # region IDependencyResolver Members29 30 public object GetService (Type serviceType) 31 {32 string contractName = AttributedModelServices. getContractName (serviceType); 33 return Container. getExportedValueOrDefault <object> (contractName); 34} 35 36 public IEnumerable <object> GetServices (Type serviceType) 37 {38 return Container. getExportedValues <object> (serviceType. fullName); 39} 40 41 # endregion42}

Initialize the MEF container in the Application_Start method of Global. asax. cs. Because the Web application only needs to find the matching in DLL, you only need to use DirectoryCatalog.

Add the MEF Attribute label to the AccountController class and delete the value assignment code of the AccountContract Attribute in the original constructor.

After the IOC component is added, our architecture becomesInterface-Oriented ProgrammingThe upper-Layer Code only depends on the lower-layer interface, but does not rely on the lower-layer implementation. To prevent the implementation code of the site business layer from appearing in the following code:

IAccountSiteContract accountContract = new AccountSiteService();

As mentioned in the previous article, the accessibility of the implementation class in the site business layer needs to beChanged from public to InternalTo isolate the upper-layer code from the lower-layer code.

Other codes remain unchanged. When you run the website, you can call the logon function normally.

V. Source Code Retrieval

GMFrameworkForBlog2.zip

In order to let everyone get the latest code of this architecture, but also to facilitate my management of the Code, the source code of this series has joined Microsoft's open source project website http://www.codeplex.com, address:

  Https://gmframework.codeplex.com/

You can obtain the latest code through the following channels:

  • If you are a participant in this project, you can directly connect to the https://tfs.codeplex.com: 443/TFS/TFS17 through the team tfs that comes with VS to get the latest code
  • If you have installed the SVN client (which is available in the test TortoiseSVN 1.6.7), you can connect to the https://gmframework.svn.codeplex.com/svn to get the latest code
  • If the above conditions are not met, you can go to the page https://gmframework.codeplex.com/SourceControl/latest to view the latest code, you can also click the Download link on the page to Download the compressed package, you can also click the History link on the page to obtain the source code of the previous version.
  • If you want to learn MVC and EF with everyone, join Q group: 5008599 (group speeches are limited to technical discussions, chat, soy sauce, and advertisement rejection)
  • If you want to work with me to complete this open-source project, you can contact me at any time.
Series navigation
  1. MVC practical Architecture Design (〇)-Overall Design
  2. MVC practical Architecture Design (I) -- project structure construction
  3. MVC practical Architecture Design (II) -- using MEF practical IOC
  4. MVC practical Architecture Design (iii) -- EF-Code First (1): Repository, UnitOfWork, DbContext
  5. MVC practical Architecture Design (iii) -- EF-Code First (2): entity ing, data migration, and Reconstruction
  6. MVC practical Architecture Design (iii) -- EF-Code First (3): generate similar Code using T4 templates
  7. MVC practical Architecture Design (iii) -- EF-Code First (4): Data Query
  8. MVC practical Architecture Design (iii) -- EF-Code First (5): Level 2 Cache
  9. MVC entity Architecture Design (4) -- Logging
  10. Not complete...

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.