美文网首页
.net core 电商项目NopCommerce 4.2学习笔

.net core 电商项目NopCommerce 4.2学习笔

作者: a9b854aded01 | 来源:发表于2019-08-26 14:22 被阅读0次

NopCommerce 4.2 是一个使用最新.net数据的开源的国外的商城项目,设计规范且代码质量很高,断断续续学习了一个周感觉还是很有研究的价值,希望整理为一个自己可以使用的通用框架,所以今天开了一个笔记记录学习遇到的问题,从同重新写一遍这个项目。

一些基础的安装和介绍参考:https://www.cnblogs.com/edisonchou/p/nop_commerce_study_part_1.html
每个模块的详细代码设计说明参考:https://www.lanhusoft.com/Article/349.html
说明很详细,虽然使用的版本很低且使用的是.net MVC但是对于理解代码的设计有很大的帮助,代码整体结构没有太大变化。

首先这次重写学习是以一个Http请求流程的方式垂直学习项目结构,如果想模块化的了解可以参考上面模块学习。

20190826

首先从注册服务和管道开始入手开始慢慢的看这个项目
Program.cs

  public static void Main(string[] args)
        {
            var host = WebHost.CreateDefaultBuilder(args)
                .UseKestrel(options => options.AddServerHeader = false)
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }

没有什么特别的正常例子 启动容器=》注册服务管道=》启动项目
可以参考:https://www.cnblogs.com/artech/p/rebuild-pipeline-01.html
Startup.cs
namespace Nop.Web

public class Startup
    {
        #region Fields

        private readonly IConfiguration _configuration;
        private readonly IHostingEnvironment _hostingEnvironment;

        #endregion

        #region Ctor

        public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
        {
            _configuration = configuration;
            _hostingEnvironment = hostingEnvironment;
        }

        #endregion

        /// <summary>
        /// Add services to the application and configure service provider
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            return services.ConfigureApplicationServices(_configuration, _hostingEnvironment);
        }

        /// <summary>
        /// Configure the application HTTP request pipeline
        /// </summary>
        /// <param name="application">Builder for configuring an application's request pipeline</param>
        public void Configure(IApplicationBuilder application)
        {
            application.ConfigureRequestPipeline();
        }

这里的服务绑定和管道绑定都是调用自己写的绑定类实现的加载,首先从service的绑定开始。

ServiceCollectionExtensions.cs
首先是主要的绑定逻辑

 /// <summary>
        /// Add services to the application and configure service provider
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Configuration of the application</param>
        /// <param name="hostingEnvironment">Hosting environment</param>
        /// <returns>Configured service provider</returns>
        public static IServiceProvider ConfigureApplicationServices(this IServiceCollection services,
            IConfiguration configuration, IHostingEnvironment hostingEnvironment)
        {
            //most of API providers require TLS 1.2 nowadays
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            //add NopConfig configuration parameters
            var nopConfig = services.ConfigureStartupConfig<NopConfig>(configuration.GetSection("Nop"));

            //add hosting configuration parameters
            services.ConfigureStartupConfig<HostingConfig>(configuration.GetSection("Hosting"));

            //add accessor to HttpContext
            services.AddHttpContextAccessor();

            //create default file provider
            CommonHelper.DefaultFileProvider = new NopFileProvider(hostingEnvironment);

            //initialize plugins
            var mvcCoreBuilder = services.AddMvcCore();
            mvcCoreBuilder.PartManager.InitializePlugins(nopConfig);

            //create engine and configure service provider
            var engine = EngineContext.Create();
            var serviceProvider = engine.ConfigureServices(services, configuration, nopConfig);

            //further actions are performed only when the database is installed
            if (!DataSettingsManager.DatabaseIsInstalled)
                return serviceProvider;

            //initialize and start schedule tasks
            TaskManager.Instance.Initialize();
            TaskManager.Instance.Start();

            //log application start
            engine.Resolve<ILogger>().Information("Application started");

            //install plugins
            engine.Resolve<IPluginService>().InstallPlugins();

            return serviceProvider;
        }

这里首先要理解IServiceCollection IConfiguration using Microsoft.Extensions.Configuration;
参考博客:https://www.cnblogs.com/nianming/p/7083964.html Config应用
https://www.cnblogs.com/artech/p/asp-net-core-di-register.html .net core服务的注册与提供
下面就是一个一个的实现

 //add NopConfig configuration parameters
            //添加nopconfig配置参数
            var nopConfig = services.ConfigureStartupConfig<NopConfig>
                (configuration.GetSection("Nop"));

实现:
 /// <summary>
        /// 创建、绑定和注册指定的配置参数作为服务
        /// </summary>
        /// <typeparam name="TConfig">Configuration parameters</typeparam>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Set of key/value application configuration properties</param>
        /// <returns>Instance of configuration parameters</returns>
        public static TConfig ConfigureStartupConfig<TConfig>(this IServiceCollection services, IConfiguration configuration) where TConfig : class, new()
        {
            if (services == null)
                throw new ArgumentNullException(nameof(services));
            if(configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            //创建配置实例
            var config = new TConfig();

            //将其绑定到配置的适当部分
            configuration.Bind(config);

            //并将其注册为服务
            services.AddSingleton(config);

            return config;
        }
appsettings.json 配置文件信息:
 "Nop": {
    //Enable if you want to see the full error in production environment. It's ignored (always enabled) in development environment
    "DisplayFullErrorStack": false,

    //Windows Azure BLOB storage.
    //Specify your connection string, container name, end point for BLOB storage here
    "AzureBlobStorageConnectionString": "",
    "AzureBlobStorageContainerName": "",
    "AzureBlobStorageEndPoint": "",
    "AzureBlobStorageAppendContainerName": "true",

    //Redis support (used by web farms, Azure, etc). Find more about it at https://azure.microsoft.com/en-us/documentation/articles/cache-dotnet-how-to-use-azure-redis-cache/
    "RedisEnabled": false,
    //Redis database id; If you need to use a specific redis database, just set its number here. Set empty if should use the different database for each data type (used by default); set -1 if you want to use the default database
    "RedisDatabaseId":  "", 
    "RedisConnectionString": "127.0.0.1:6379,ssl=False",
    "UseRedisToStoreDataProtectionKeys": false,
    "UseRedisForCaching": false,
    "UseRedisToStorePluginsInfo": false,

    //You can get the latest version of user agent strings at http://browscap.org/
    //Leave "CrawlersOnlyDatabasePath" attribute empty if you want to use full version of "browscap.xml" file
    "UserAgentStringsPath": "~/App_Data/browscap.xml",
    "CrawlerOnlyUserAgentStringsPath": "~/App_Data/browscap.crawlersonly.xml",

    //Do not edit this element. For advanced users only
    "DisableSampleDataDuringInstallation": false,
    "UseFastInstallationService": false,
    "PluginsIgnoredDuringInstallation": "",

    //Enable if you want to clear /Plugins/bin directory on application startup
    "ClearPluginShadowDirectoryOnStartup": true,
    //Enable if you want to copy "locked" assemblies from /Plugins/bin directory to temporary subdirectories on application startup
    "CopyLockedPluginAssembilesToSubdirectoriesOnStartup": false,
    //Enable if you want to copy plugins library to the /Plugins/bin directory on application startup
    "UsePluginsShadowCopy": true,
    //Enable if you want to load an assembly into the load-from context, by passing some security checks
    "UseUnsafeLoadAssembly": true,

    //Enable for backwards compatibility with SQL Server 2008 and SQL Server 2008R2
    "UseRowNumberForPaging": false,

    //Enable to store TempData in the session state
    "UseSessionStateTempDataProvider": false
  }

以上面为例
这样完成了一个配置文件信息和一个实例模型的绑定。
然后附加到httpconxt

//add accessor to HttpContext
            //附加到httpconxt
            services.AddHttpContextAccessor();

 public static void AddHttpContextAccessor(this IServiceCollection services)
        {
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        }

20190826
然后绑定的是文件帮助类

 //create default file provider
            //创建默认文件提供程序
            CommonHelper.DefaultFileProvider = new NopFileProvider(hostingEnvironment);

下面Core里面添加了一个CommonHelper通用的帮助类、INopFileProvider NopFileProvider  对文件操作的帮助类
看一下INopFileProvider里面包含了所有对文件的操作
所在namespace :
namespace Nop.Core.Infrastructure

相关文章

网友评论

      本文标题:.net core 电商项目NopCommerce 4.2学习笔

      本文链接:https://www.haomeiwen.com/subject/ybbrectx.html