本节将通过对“2019-10-30_MyNopCommerce_VS19Core2.2Nop4.20(不删012_授权)”程序进行重构,从而来实现授权功能。
- 添加如图中所选择类的定义:
- 重构Nop.Services.Installation.CodeFirstInstallationService类
(1)、重构InstallCustomersAndUsers(string defaultUserEmail, string defaultUserPassword)方法,在此方法中添加语句:
//设置默认用户名。
_genericAttributeService.SaveAttribute(adminUser, NopCustomerDefaults.FirstNameAttribute, "John");
_genericAttributeService.SaveAttribute(adminUser, NopCustomerDefaults.LastNameAttribute, "Smith");
(2)、添加方法 InstallScheduleTasks()和InstallLanguages();的定义。
(3)、重构public virtual void InstallRequiredData(string defaultUserEmail, string defaultUserPassword) 方法,在此方法中添加语句:
InstallScheduleTasks();
InstallLanguages();
- 重构Nop.Web.Framework.Infrastructure.DependencyRegistrar类
在 public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder)方法中,添加下列语句: builder.RegisterType<GenericAttributeService>().As<IGenericAttributeService>().InstancePerLifetimeScope();44、并按F5可以发现数据库中的GenericAttribute、Language和ScheduleTask表中的数据已经被初始化。
5、重构WebHelper和IWebHelper添加方法GetStoreLocation和GetStoreHost方法的声明和定义。
6、添加IStoreContext和WebStoreContext的声明和定义
7、重构StoreService和IStoreService添加方法GetAllStores、GetStoreById、ContainsHostValue和ParseHostValues方法的声明和定义。
8、重构Nop.Web.Framework.Infrastructure.DependencyRegistrar类
在 public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder)方法中,添加下列语句:
//电子商店上下文
builder.RegisterType<WebStoreContext>().As<IStoreContext>().InstancePerLifetimeScope();
9、Nop.Services.Installation.CodeFirstInstallationService类中的InstallStores()方法为:
//var storeUrl = "http://www.yourStore.com/";
var storeUrl = _webHelper.GetStoreLocation(false);
10、重构Nop.Web.Framework.Infrastructure.DependencyRegistrar类,重新定义 private static IComponentRegistration BuildRegistration<TSettings>() where TSettings : ISettings, new()方法为:
//如果要初始化数据,则取消以下注释。
//return RegistrationBuilder
// .ForDelegate((c, p) =>
// {
// //尽管最好连接到数据库并执行以下SQL:
// //DELETE FROM [Setting] WHERE [StoreId] > 0
// return c.Resolve<ISettingService>().LoadSetting<TSettings>(0);
// })
// .InstancePerLifetimeScope()
// .CreateRegistration();
//如果要初始化数据,则要将以下注释。
return RegistrationBuilder
.ForDelegate((c, p) =>
{
var currentStoreId = c.Resolve<IStoreContext>().CurrentStore.Id;
//尽管最好连接到数据库并执行以下SQL:
// //DELETE FROM [Setting] WHERE [StoreId] > 0
return c.Resolve<ISettingService>().LoadSetting<TSettings>(currentStoreId);
})
.InstancePerLifetimeScope()
.CreateRegistration();
11、添加断点到return c.Resolve<ISettingService>().LoadSetting<TSettings>(currentStoreId);
12、并按F5可以发现currentStoreId的值为1。
13、新详细的信息请见我所上传代码“2019-11-05_MyNopCommerce_VS19Core2.2Nop4.20(不删,013_重构DependencyRegistrar)。(https://download.csdn.net/download/zhoujian_911/11958595)”