In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about sample analysis based on nopCommerce development framework. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Net developers should know that this famous high-quality B2C open source project, nopCommerce, is based on EntityFramework and MVC development, has a transparent and well-structured solution, and combines the best features of open source and commercial software. Official website address: http://www.nopcommerce.com/, Chinese website: http://www.nopcn.com/. The front and rear end of the download is shown below. If you don't already know about the project, it is recommended to download the code from the official website and run it locally to check the results.
First, understand the project structure
From the project structure diagram, we can also see that the hierarchical division of Nop is very clear. Let's take a look at the hierarchical diagram I drew first.
1. Presentation layer (Presentation)
It can also be called the application layer, which only focuses on the integration of the front end and does not involve any domain logic implementation. This layer is only for presentation and is optional to our framework, so it will be deleted when the framework is extracted.
two。 Business Services layer (Nop.Services)
The service layer of the whole system provides interfaces and implementations for each domain. This layer is very important and provides interface services to the presentation layer within the program. This layer service is required regardless of whether the presentation layer uses mvc or winform, or the webapi interface called for app. However, the services in this layer are mainly e-commerce services, which are of no use to our framework, so all services will be deleted in this framework, only a test service class and interface will be added, and when applied to the project, you should add interfaces and services to this layer.
3. Data layer (Nop.Data)
Nop uses ef and sqlserver databases in the warehousing implementation of the data tier, and if you want to extend it, you can also use other ORM mapping libraries and databases at this tier. We will retain most of the functions of this layer in the framework.
4. Infrastructure layer (Nop.Core)
It includes the implementation of cache, configuration, domain model and so on. In the framework will retain part of the function, and move the Domain domain model out of this layer to do a separate project, why do so, because usually, the Domain layer adjustment will be more, so I usually will Domain do a separate Project, of course, you can not adjust, but the framework made the adjustment.
Delete the code related to the business
We already have an understanding of the entire code hierarchy of Nop, and begin to modify the project source code based on the following two points: 1. The framework is concise enough that there is no e-commerce business. two。 Core functions are retained. It is recommended to copy a copy of the source code before starting.
1. Test project: under the Tests folder is the test project, which is not required. Remove it all, develop specific business, and then add the test project separately. Because it is a test project, the whole project can still run after deletion.
2. Presentation presentation layer: the three projects here are the foreground, the backend and some modules shared by the two projects. Like the test project, we remove it all here.
3. Plugin project: plug-in projects, like 1 and 2, plug-ins are not required, remove all plug-in projects. Now there are only three projects left (welcome to follow the github of this project, and I will write a special article on how to add plug-ins later).
Nop.Services: business services layer, which is the internal and external interface layer of the assembly and needs to be retained. Delete all relevant business service classes, including logs, help, tasks, etc. related to the system, in order to better show the structure of the whole system. Add a test class and write nothing for the time being.
Nop.Data: data layer project. This layer basically does not adjust, only removes the Mapping mapping related classes of EF.
Nop.Core: infrastructure layer. Delete the Domain related to e-commerce business and create a new project Nop.Domain.
If an error has been reported, IWorkContext (work context, used to obtain data such as user information) depends on Domain, delete it. This process may have to delete many files until the project no longer reports an error. After the completion of our project structure is as follows, notice that we moved the entity base classes in Nop.Core to Nop.Domain, to this step, our basic framework structure has been roughly out.
Add database, data entity, mapping, business layer code
1. In the local Sqlserver, create a new database MyProject and add the table Test.
USE [MyProject] GO / * Object: Table [dbo]. [Test] Script Date: 05gamma 23:51:21 * / SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo]. [Test] ([Id] [int] NOT NULL, [Name] [nvarchar] (50) NOT NULL, [Description] [nvarchar] (200) NULL, [CreateDate] [datetime] NULL,CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED [Id] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]
two。 Add entity classes and mappings. Create a new Test directory under the Domain project and add TestEntity. Create a new Test directory under the Data project Mapping and add the EF mapping class.
Public class TestEntity: BaseEntity {public virtual string Name {get; set;} public virtual string Description {get; set;} public virtual DateTime? CreateDate {get; set;}}
3. Add a business layer method.
In the Nop.Services project, add a few commonly used CURD methods under the interfaces and classes we added earlier, and implement it. In this way, we have implemented the business layer code.
/ Test service interface/// public partial interface ITestService {/ Gets all tests/// TestsIList GetAllTests (); / Gets a test/// The test identifier/// TestTestEntity GetTestById (int testId); / Inserts a test/// Testvoid InsertTest (TestEntity test); / Updates the test/// Testvoid UpdateTest (TestEntity test) / Deletes a test/// Testvoid DeleteTest (TestEntity test);} / Test service/// public partial class TestService: ITestService {# region Constants#endregion#region Fields private readonly IRepository _ testRepository;#endregion#region Ctorpublic TestService (IRepository testRepository) {this._testRepository = testRepository;} # endregion#region Methods / Gets all tests/// Testspublic virtual IList GetAllTests () {return _ testRepository.Table.Where (p = > p.Name! = null). ToList () } / Gets a topic/// The test identifier/// Testpublic virtual TestEntity GetTestById (int testId) {if (testId = = 0) return null;return _ testRepository.GetById (testId);} / Inserts a test/// Testpublic virtual void InsertTest (TestEntity test) {if (test = = null) throw new ArgumentNullException ("test"); _ testRepository.Insert (test) / Updates the test/// Testpublic virtual void UpdateTest (TestEntity test) {if (test = = null) throw new ArgumentNullException ("test"); _ testRepository.Update (test);} / Deletes a test/// Testpublic virtual void DeleteTest (TestEntity test) {if (test = = null) throw new ArgumentNullException ("test"); _ testRepository.Delete (test);} # endregion}
Add Presentation project
With the business services, you can now add a presentation layer project to test. Why not just write the test project? Because the test project uses Mock to simulate data, it can not fully demonstrate the whole function.
1. Add the mvc template project and introduce Autofac and Autofac.Mvc5 through nuget.
two。 Add the container registration class DependencyRegistrar to implement the IDependencyRegistrar interface, which is critical. The interface and implementation class we are going to use are injected into the container.
/ Dependency registrar/// public class DependencyRegistrar: IDependencyRegistrar {/ Register services and interfaces/// Container builder/// Type finder/// Configpublic virtual void Register (ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config) {/ / inject ObjectContextbuilder.Register (c = > new NopObjectContext ("test"). InstancePerLifetimeScope (); / / inject ef into warehouse builder.RegisterGeneric (typeof (EfRepository)) .as (typeof (IRepository)). InstancePerLifetimeScope () / / inject Service and interface builder.RegisterAssemblyTypes (typeof (TestService) .Assembly). AsImplementedInterfaces (). InstancePerLifetimeScope (); / / inject controllersbuilder.RegisterControllers (typeFinder.GetAssemblies (). ToArray ());} / Order of this dependency registrar implementation/// public int Order {get {return 2;}
3. Add a database access node to the configuration file
The copy code is as follows:
4. Add the initialization engine context when the application starts
When you start the project, NopEngine will report an error because we did not use Nopconfig to configure the project, annotate the injection of NopConfig in the RegisterDependencies method, and comment the related code during the Initialize process. This completes injecting the class into the container through Autofac.
Public class MvcApplication: System.Web.HttpApplication {protected void Application_Start () {AreaRegistration.RegisterAllAreas (); FilterConfig.RegisterGlobalFilters (GlobalFilters.Filters); RouteConfig.RegisterRoutes (RouteTable.Routes); BundleConfig.RegisterBundles (BundleTable.Bundles); / / engine context initialization EngineContext.Initialize (false);}} / / RegisterDependencies method annotation NopConfig injection / / builder.RegisterInstance (config). As (). SingleInstance (); public void Initialize (NopConfig config) {/ / register dependenciesRegisterDependencies (config) / / do not use config, temporarily comment / / register mapper configurations//RegisterMapperConfiguration (config); / / startup tasks does not enable the task, note / / if (! config.IgnoreStartupTasks) / / {/ / RunStartupTasks (); / /}}
5. Add test code to controller. Add service to HomeController and initialize it in the constructor. The instance is automatically injected after the system starts. Through the breakpoint, we can see that the data was successfully added to the database.
Public class HomeController: Controller {public ITestService _ testService;public HomeController (ITestService testService) {_ testService = testService;} public ActionResult Index () {var entity = new TestEntity () {CreateDate = DateTime.Now,Description = "description 2", Name = "Test data 2"}; _ testService.InsertTest (entity); var tests = _ testService.GetAllTests (); return View ();}
Expand to Webapi, Winform, WPF
Now add another winform project, and add the relevant code in the same step. We can also use business services in Winform.
1. Install autofac,entityframework through Nuget and add a reference under the project Libraries.
two。 Add dependent registration class, because it is a winform project, DependencyRegistrar needs to make some adjustments here. It is recommended to define an empty interface IRegistrarForm, which requires injected Form to implement IRegistrarForm.
/ Dependency registrar/// public class DependencyRegistrar: IDependencyRegistrar {/ Register services and interfaces/// Container builder/// Type finder/// Configpublic virtual void Register (ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config) {/ / inject ObjectContextbuilder.Register (c = > new NopObjectContext ("test"). InstancePerLifetimeScope (); / / inject ef into warehouse builder.RegisterGeneric (typeof (EfRepository)) .as (typeof (IRepository)). InstancePerLifetimeScope () / injection Service and interface builder.RegisterAssemblyTypes (typeof (TestService) .Assembly). AsImplementedInterfaces (). InstancePerLifetimeScope (); / injection controllers//builder.RegisterControllers (typeFinder.GetAssemblies (). ToArray ()); / / injection formsvar types = AppDomain.CurrentDomain.GetAssemblies (). SelectMany (a = > a.GetTypes (). Where (t = > t.GetInterfaces (). Contains (typeof (IRegistrarForm). ToArray (); foreach (var formtype in types) {builder.RegisterAssemblyTypes (formtype.Assembly) }} / Order of this dependency registrar implementation/// public int Order {get {return 2;}
3. Add EngineContext.Initialize (false) at startup, start the project, report an error, because winform cannot be executed, make some adjustments to the method, add a parameter isForm to indicate whether it is winform, the default is false.
/ Initializes a static instance of the Nop factory. / Creates a new factory instance even though the factory has been previously initialized. / / whether the client program [MethodImpl (MethodImplOptions.Synchronized)] public static IEngine Initialize (bool forceRecreate,bool isWinForm = false) {if (Singleton.Instance = = null | | forceRecreate) {Singleton.Instance = new NopEngine (); NopConfig config = null; if (! isWinForm) {config = ConfigurationManager.GetSection ("NopConfig") as NopConfig } else {/ / if using winform, use this code to read the configuration initialization NopConfig var appSettings = ConfigurationManager.AppSettings; foreach (var key in appSettings.AllKeys) {}} Singleton.Instance.Initialize (config);} return Singleton.Instance;} static class Program {/ the main entry point of the application. / / [STAThread] static void Main () {Application.EnableVisualStyles (); Application.SetCompatibleTextRenderingDefault (false); / / Application.Run (new Form1 ()); / / engine context initialization EngineContext.Initialize (false, true); Application.Run (EngineContext.Current.Resolve ());}}
4. After testing in From1, we successfully called the method of the business layer. Instead of instantiating ITestService, we handed it over to the automatic implementation of dependency injection.
Public partial class Form1: Form, IRegistrarForm {private ITestService _ testService;public Form1 (ITestService testService) {InitializeComponent (); _ testService = testService;// if you don't inject form, you can use EngineContext.Current.Resolve (); get an instance} private void button1_Click (object sender, EventArgs e) {var tests = _ testService.GetAllTests ();}} Thank you for reading! This is the end of this article on "sample Analysis based on nopCommerce Development Framework". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.