NopCommerce 4.2 是一個使用最新.net數(shù)據(jù)的開源的國外的商城項目,設計規(guī)范且代碼質(zhì)量很高,斷斷續(xù)續(xù)學習了一個周感覺還是很有研究的價值,希望整理為一個自己可以使用的通用框架,所以今天開了一個筆記記錄學習遇到的問題,從同重新寫一遍這個項目。
一些基礎的安裝和介紹參考:https://www.cnblogs.com/edisonchou/p/nop_commerce_study_part_1.html
每個模塊的詳細代碼設計說明參考:https://www.lanhusoft.com/Article/349.html
說明很詳細,雖然使用的版本很低且使用的是.net MVC但是對于理解代碼的設計有很大的幫助,代碼整體結(jié)構沒有太大變化。
首先這次重寫學習是以一個Http請求流程的方式垂直學習項目結(jié)構,如果想模塊化的了解可以參考上面模塊學習。
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();
}
這里的服務綁定和管道綁定都是調(diào)用自己寫的綁定類實現(xiàn)的加載,首先從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服務的注冊與提供
下面就是一個一個的實現(xiàn)
//add NopConfig configuration parameters
//添加nopconfig配置參數(shù)
var nopConfig = services.ConfigureStartupConfig<NopConfig>
(configuration.GetSection("Nop"));
實現(xiàn):
/// <summary>
/// 創(chuàng)建、綁定和注冊指定的配置參數(shù)作為服務
/// </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));
}
//創(chuàng)建配置實例
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
//創(chuàng)建默認文件提供程序
CommonHelper.DefaultFileProvider = new NopFileProvider(hostingEnvironment);
下面Core里面添加了一個CommonHelper通用的幫助類、INopFileProvider NopFileProvider 對文件操作的幫助類
看一下INopFileProvider里面包含了所有對文件的操作
所在namespace :
namespace Nop.Core.Infrastructure