"Open source" Osharp Frame Commentary series (4): Architecture layering and IOC

Source: Internet
Author: User

0. Preface

A background management interface layout has been constructed, and a hierarchical design of the entire project is described below.

On the hierarchy, there are already quite a lot of discussions on the Internet, which is also the first problem that a programmer will encounter in the architecture design.

    • Should it be layered?
    • How to Tier?
    • Is there a need for decoupling between layers and layers? Do you need to design an interface? Is the interface redundant?

After reading the layered design of osharp, I think you should be able to get some inspiration.

Note: The predecessor of the Osharp Development Framework is the architecture example described in the MVC Entity Architecture Design Series, so there are a lot of knowledge points in that series that are not duplicated in this series, and if there is anything that you don't understand, you can refer to the MVC Entity Architecture Design Series.

First, Directory

0. Preface

First, Directory

Second, the framework of the overall layered design

Three, layered decoupling and dependency injection

Iv. Open Source Instructions

Series Navigation

Second, the framework of the overall layered design should not be layered and the benefits of layering

On the merits of layering and layering, there has been quite a lot of discussion on the Internet, and we will not repeat it here. Quoted here is a more representative article, "The advantages and disadvantages of layered structure" for reference, the full text is as follows:

What are the advantages of layered structure? Martin Fowler the answer in the book Patterns of Enterprise application Architecture:

  1. A developer can focus on only one of the layers in the entire structure;
  2. can easily replace the implementation of the original level with the new implementation;
  3. Can reduce the dependence between layer and layer;
  4. conducive to standardization;
  5. Facilitates the reuse of all layers of logic.

In summary, layered design can achieve the following objectives: Decentralized attention, loose coupling, logical multiplexing, and standard definitions.

A good layered structure can make the developer's Division of labor more explicit. Once the interfaces between the various levels are defined, developers who are responsible for different logic designs can distract and go hand in hand. For example, UI staff only need to consider the user interface experience and operation, the domain designer can focus only on the design of business logic, and database designers do not have to be cumbersome user interaction and headache. Each developer's task is confirmed and development progress can be improved quickly.

The benefits of loose coupling are obvious. If a system does not have a hierarchy, then the respective logic is tightly intertwined, interdependent with each other, who can not be replaced. Once the change occurs, the reaching, the impact on the project is extremely serious. Reducing the dependency between layers and layers can not only guarantee the future scalability, but also have obvious advantages in reusability. Once each function module has a unified interface defined, it can be called by each module without having to develop the same functionality repeatedly.

The standard is also essential for the design of a good layered structure. Only on the basis of a certain degree of standardization, the system is extensible, replaceable. The communication between layers and layers must also ensure the standardization of interfaces.

Layered structures also have some drawbacks:

  1. Reduces the performance of the system. This is self-evident. Without a tiered structure, many businesses can access the database directly to get the data, and now they have to do it through the middle tier.
  2. This can sometimes lead to cascading changes. This kind of modification is especially reflected in the top-down direction. If you need to add a feature in the presentation layer to ensure that the design conforms to the layered structure, you may need to add code to the appropriate business logic layer and the data access layer.
Layering and interface-oriented programming

Talking about the interface between the layers, there will probably be a lot of students to spit out the slot, do not want to use the interface, the reason is as follows:

    • Defining an interface results in a project layering too much, adding a module, adding a lot of class files and code, and increasing the workload of developers
    • A single implementation of the interface, the actual use of little, but when reading the code, the interface causes "go To Definition" can only go to the interface, the implementation of the class has to be found manually.

The above is a common reason to refuse to use an interface.

However, from my personal point of view, the pros and cons of using the interface are far outweigh the disadvantages:

    • One of the benefits of using interfaces is decoupling dependencies at all levels, allowing us to easily replace "concrete implementations" (the benefit is not obvious for most projects)
    • Interface is the skeleton of the project, is the overall embodiment of the architecture, the architect in the construction of the project, the direct definition of the interface at all levels, the entire project's main skeleton design, then developers only need to "fill in the blanks" way to achieve a variety of methods, can greatly improve the development efficiency, and ensure the integrity and rationality of the project
    • In the level of unit testing, because each level is interface isolation, the upper layer does not rely on the implementation of the lower layer, when testing the upper layer, as long as the use of MOQ, fakes and other mock frame to the lower interface to simulate, it can be very easy to test the upper layer of business implementation. If the upper layer is tightly coupled with the lower layer, the upper layer code is almost impossible to test. (If you don't know the unit test, you can look at the two articles I wrote: TDD based on VS2012 fakes framework)

Add: About whether the interface has the necessary discussion, there is a post on iteye.com a very enthusiastic discussion, strongly recommend to look at:

Topic: How is layering in the project architecture most plausible?

Layered design of Osharp

The layered scheme agreed by the Osharp development framework is still a layered approach of the traditional three layer (data layer-business Layer-presentation layer), but it also has its own characteristics:

    • Three layers of layering are used, but not strictly in accordance with the traditional three-layer "all layers of responsibility is very distinct" agreement
    • Refer to some ideas of "domain driven design", but to ensure performance, do not use the DDD aggregation model
Data layer:

  

As shown, the role of the Osharp data layer is to provide the business layer with a database persistence operation for the data entity, providing a query dataset to the business and presentation layers for querying data. External API is very simple, mainly iunitofwork and irepository<tentity> two interfaces, while defining the support of generic primary key types of the entity model base class EntityBase, data transmission object Interface Iadddto and Ieditdto.

Business layer:

  

The business layer of OSHARP is divided into modules, a module is an operating unit consisting of one or more entities in the business , consisting of three parts:

    1. The definition of the data entity model, the data model is the data interaction object between the business layer and the data layer, and the object that the data layer is persisted, which is the final bearer of the business data.
    2. Data Transfer object (DTO) definition, data transfer object is a presentation layer to the business layer of interaction objects, DTOs can be used as a view model when needed to display on the page.
    3. The definition of the Business Processing module, the Business processing module includes the definition of the business contract (IXXXCONTRACT) and the implementation of the business logic (Ixxxservice). The Business Processing module accepts the data from a Dto in the presentation layer and, after business processing, transforms it into model submission to the data layer for persistence. The Business Processing module also provides the presentation layer with the iqueryable<tentity> type of query data set for the corresponding entity, as the data source for the presentation layer to query data. In principle, the business processing module only handles inserting, updating and deleting data, and does not provide data query service to the presentation layer.

The business layer has the following characteristics:

    1. The business layer accepts parameters from the presentation layer as DTOs or simple type parameters
    2. Business layer returns to presentation layer business operation result as Operationresult type
    3. Business Layer only handles insert, modify, delete and other non-query business, in principle does not provide the presentation layer data query business
    4. The business layer opens the query data set of the iqueryable<t> type of the corresponding entity to the presentation layer as the query data source for the presentation layer
    5. The conversion of DTOs and Model is done by AutoMapper.
    6. Model construction is done by the business layer, and the presentation layer provides the necessary dtos to the business layer and does not participate in the model's construction work.
Presentation layer:

  

The presentation layer of MVC contains two parts of the controller and the Views (view). The controller is responsible for using the open query data set of the business layer to perform the data query operation, then submits the query results to the view to display, and is responsible for receiving the data from the view submission, converting it to the Dto to submit to the business layer for processing. The Business Processing results (Operationresult) that receive and parse the business layer feedback are presented to the user by the view. The view receives and resolves the data passed by the controller, parses it into an HTML page that is sent to the browser for presentation, and submits the user's request data to the controller.

In this article, just a brief explanation of the stratification, from the overall understanding of the osharp layered architecture, in the back into the actual application, but also to the various layers of more detailed analysis.

Three, layered decoupling and dependency injection

The need for decoupling has been analyzed earlier, so how is decoupling in the OSHARP development framework implemented? The decoupling work in Osharp is accomplished mainly by AUTOFAC the IoC component. AUTOFAC is a lightweight IOC component that is very small in system pollution and intrusion, and has very good support for mainstream ASP. NET Web technologies such as Webform, MVC, WebApi, SIGNALR, etc., and is a fairly good IOC component.

To unify the management of IoC-related code and avoid referencing AUTOFAC as a third-party component in the Osharp underlying class library, OSHARP defines an empty interface that is specifically designed to manage interfaces and implementation classes that require dependency injection idependency:

1  /// <summary> 2  /// The Dependency Injection interface, which indicates that the implementation class for the interface is automatically registered in the IOC container 3  /// </summary> 4   Public Interface idependency 5  { }

This interface does not have any method, does not pollute the system's business logic, all needs to carry on the dependency injection the interface, all must inherit this empty interface, for example:

Business Unit Operation Interface:

1 /// <summary> 2 /// Business Unit Operation Interface 3 /// </summary> 4  Public Interface iunitofwork:idependency 5 {6    ... 7 }

Entity Warehousing Operation Interface:

1 /// <summary>2 ///Data standard operation of entity Warehousing model3 /// </summary>4 /// <typeparam name= "TEntity" >entity Type</typeparam>5 /// <typeparam name= "TKey" >primary Key Type</typeparam>6  Public InterfaceIrepository<tentity, tkey>: idependencywhereTentity:entitybase<tkey>7 {8     ...9}

Account Module Business contract:

1 /// <summary> 2 /// Business Contract--account module 3 /// </summary> 4  Public Interface iidentitycontract:idependency 5 {6    ... 7 }

In the place where you need to reference the injected object, use the "constructor injection" method to inject it uniformly.

Entity warehousing Implementation class:

1 /// <summary>2 ///warehousing Implementation of EntityFramework3 /// </summary>4 /// <typeparam name= "TEntity" >entity Type</typeparam>5 /// <typeparam name= "TKey" >primary Key Type</typeparam>6  Public classRepository<tentity, tkey>: irepository<tentity, tkey>whereTentity:entitybase<tkey>7 {    8     Private ReadOnlyiunitofwork _unitofwork;9 Ten      PublicRepository (iunitofwork unitofwork) One     { A_unitofwork =unitofwork; -     } -  the     ... -       -}

Account Module Business Implementation class:

1 /// <summary>2 ///Business Implementation--account module3 /// </summary>4  Public Partial classIdentityservice:servicebase, Iidentitycontract5 {6     Private ReadOnlyIrepository<user,int>_userrepository;7     Private ReadOnlyIrepository<role,int>_rolerepository;8     Private ReadOnlyIrepository<organization,int>_organizationrepository;9 Ten     /// <summary> One     ///Initializes a<see cref= "Identityservice"/>new instances of type A     /// </summary> -      PublicIdentityservice (Irepository<user,int>Userrepository, -Irepository<role,int>Rolerepository, theIrepository<organization,int>organizationrepository) -:Base(userrepository.unitofwork) -     { -_userrepository =userrepository; +_rolerepository =rolerepository; -_organizationrepository =organizationrepository; +     } A}

AUTOFAC is to support batch Quantum class registration, with Idependency This base interface, we only need a few lines of a simple line of code in Global, we can complete the whole system of dependency injection matching:

1Containerbuilder Builder =NewContainerbuilder ();2Builder. Registergeneric (typeof(repository<,>)). As (typeof(irepository<,>));3Type BaseType =typeof(idependency);4 5 //get the assemblies for all related class libraries6Assembly[] Assemblies = ...7 8 Builder. Registerassemblytypes (Assemblies)9. Where (type = Basetype.isassignablefrom (type) &&!type. IsAbstract)Ten. Asimplementedinterfaces (). Instanceperlifetimescope ();//Instanceperlifetimescope guarantee that the object life cycle is based on request OneIContainer container =Builder. Build (); ADependencyresolver.setresolver (NewAutofacdependencyresolver (container));

Thus, only the site main class library needs to refer to AUTOFAC, rather than the presence of injected code everywhere, greatly reducing the complexity of the system.

Iv. Open Source Instructions (i) github.com

Osharp Project has open source on github.com, address: https://github.com/i66soft/osharp, welcome to read the code, Welcome to Fork, if you agree with the idea of Osharp project, welcome to participate in the development of OSHARP project.

In Visual Studio 2013, you can get the latest source code for OSHARP directly, with the following address: Https://github.com/i66soft/osharp.git

  

(ii) NuGet

Osharp's related libraries have been published on NuGet and are welcome to try and search for "osharp" keywords directly on NuGet to find
  

Series Navigation
    1. "Open source" Osharp frame Commentary Series (1): Overall design
    2. "Open source" Osharp frame Commentary Series (2.1): Easyui's background interface and extreme refactoring
    3. "Open source" Osharp Frame Commentary Series (2.2): Easyui complex layout and data manipulation
    4. "Open source" Osharp Frame Commentary Series (3): extension method
    5. "Open source" Osharp Frame Commentary series (4): Architecture layering and IOC
    6. "Open source" Osharp Frame Commentary Series (5.1): Data layer Design
    7. "Open source" Osharp frame Commentary Series (5.2): EntityFramework Package

"Open source" Osharp Frame Commentary series (4): Architecture layering and IOC

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.