Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

Refactor/WorkContextAccessor (#549)

Krzysztof Pajak68790b994541
diff --git a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs
index 94b649180..ecb0fa610 100644
--- a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs
+++ b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs
@@ -31,7 +31,7 @@ public class ExternalAuthenticationService : IExternalAuthenticationService
IGroupService groupService,
IMediator mediator,
IRepository<ExternalAuthentication> externalAuthenticationRecordRepository,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IEnumerable<IExternalAuthenticationProvider> externalAuthenticationProviders,
CustomerSettings customerSettings,
ExternalAuthenticationSettings externalAuthenticationSettings)
@@ -44,7 +44,7 @@ public class ExternalAuthenticationService : IExternalAuthenticationService
_groupService = groupService;
_mediator = mediator;
_externalAuthenticationRecordRepository = externalAuthenticationRecordRepository;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_externalAuthenticationProviders = externalAuthenticationProviders;
}
@@ -58,7 +58,7 @@ public class ExternalAuthenticationService : IExternalAuthenticationService
private readonly IGroupService _groupService;
private readonly IMediator _mediator;
private readonly IRepository<ExternalAuthentication> _externalAuthenticationRecordRepository;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IEnumerable<IExternalAuthenticationProvider> _externalAuthenticationProviders;
private readonly CustomerSettings _customerSettings;
private readonly ExternalAuthenticationSettings _externalAuthenticationSettings;
@@ -130,24 +130,24 @@ public class ExternalAuthenticationService : IExternalAuthenticationService
or UserRegistrationType.EmailValidation;
//create registration request
- var registrationRequest = new RegistrationRequest(_workContext.CurrentCustomer,
+ var registrationRequest = new RegistrationRequest(_workContextAccessor.WorkContext.CurrentCustomer,
parameters.Email, parameters.Email,
CommonHelper.GenerateRandomDigitCode(20),
PasswordFormat.Hashed,
- _workContext.CurrentStore.Id,
+ _workContextAccessor.WorkContext.CurrentStore.Id,
approved);
//whether registration request has been completed successfully
await _customerManagerService.RegisterCustomer(registrationRequest);
//allow to save other customer values by consuming this event
- await _mediator.Publish(new RegisteredByExternalMethod(_workContext.CurrentCustomer, parameters));
+ await _mediator.Publish(new RegisteredByExternalMethod(_workContextAccessor.WorkContext.CurrentCustomer, parameters));
//raise customer registered event
- await _mediator.Publish(new CustomerRegisteredEvent(_workContext.CurrentCustomer));
+ await _mediator.Publish(new CustomerRegisteredEvent(_workContextAccessor.WorkContext.CurrentCustomer));
//associate external account with registered user
- await AssociateCustomer(_workContext.CurrentCustomer, parameters);
+ await AssociateCustomer(_workContextAccessor.WorkContext.CurrentCustomer, parameters);
//authenticate
if (!approved)
@@ -155,7 +155,7 @@ public class ExternalAuthenticationService : IExternalAuthenticationService
? new RedirectToRouteResult("RegisterResult",
new { resultId = (int)UserRegistrationType.AdminApproval })
: Error(["Error on registration"]);
- await _authenticationService.SignIn(_workContext.CurrentCustomer, false);
+ await _authenticationService.SignIn(_workContextAccessor.WorkContext.CurrentCustomer, false);
return new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.Standard });
}
@@ -206,8 +206,8 @@ public class ExternalAuthenticationService : IExternalAuthenticationService
return LoadAllAuthenticationProviders()
.Where(provider =>
provider.IsMethodActive(_externalAuthenticationSettings) &&
- provider.IsAuthenticateGroup(_workContext.CurrentCustomer) &&
- provider.IsAuthenticateStore(_workContext.CurrentStore)
+ provider.IsAuthenticateGroup(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ provider.IsAuthenticateStore(_workContextAccessor.WorkContext.CurrentStore)
).ToList();
}
@@ -242,8 +242,8 @@ public class ExternalAuthenticationService : IExternalAuthenticationService
return authenticationMethod != null &&
authenticationMethod.IsMethodActive(_externalAuthenticationSettings) &&
- authenticationMethod.IsAuthenticateGroup(_workContext.CurrentCustomer) &&
- authenticationMethod.IsAuthenticateStore(_workContext.CurrentStore);
+ authenticationMethod.IsAuthenticateGroup(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ authenticationMethod.IsAuthenticateStore(_workContextAccessor.WorkContext.CurrentStore);
}
#endregion
@@ -264,8 +264,8 @@ public class ExternalAuthenticationService : IExternalAuthenticationService
return Error(["External authentication method cannot be loaded"]);
//get current logged-in user
- var currentLoggedInUser = await _groupService.IsRegistered(_workContext.CurrentCustomer)
- ? _workContext.CurrentCustomer
+ var currentLoggedInUser = await _groupService.IsRegistered(_workContextAccessor.WorkContext.CurrentCustomer)
+ ? _workContextAccessor.WorkContext.CurrentCustomer
: null;
//authenticate associated user if already exists
diff --git a/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs
index e719858c7..1b2f7177a 100644
--- a/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs
+++ b/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs
@@ -14,14 +14,14 @@ public class TwoFactorAuthenticationService : ITwoFactorAuthenticationService
private readonly IEnumerable<ISMSVerificationService> _smsVerificationService;
private readonly TwoFactorAuthenticator _twoFactorAuthentication;
private readonly ICustomerService _customerService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public TwoFactorAuthenticationService(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ICustomerService customerService,
IEnumerable<ISMSVerificationService> smsVerificationService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_customerService = customerService;
_smsVerificationService = smsVerificationService;
_twoFactorAuthentication = new TwoFactorAuthenticator();
@@ -62,7 +62,7 @@ public class TwoFactorAuthenticationService : ITwoFactorAuthenticationService
switch (twoFactorAuthenticationType)
{
case TwoFactorAuthenticationType.AppVerification:
- var setupInfo = _twoFactorAuthentication.GenerateSetupCode(_workContext.CurrentStore.CompanyName,
+ var setupInfo = _twoFactorAuthentication.GenerateSetupCode(_workContextAccessor.WorkContext.CurrentStore.CompanyName,
customer.Email, secretKey, false);
model.CustomValues.Add("QrCodeImageUrl", setupInfo.QrCodeSetupImageUrl);
model.CustomValues.Add("ManualEntryQrCode", setupInfo.ManualEntryKey);
diff --git a/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs b/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs
index e4931620d..00bfb3cea 100644
--- a/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs
@@ -24,12 +24,12 @@ public class BrandService : IBrandService
/// </summary>
public BrandService(ICacheBase cacheBase,
IRepository<Brand> brandRepository,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator, AccessControlConfig accessControlConfig)
{
_cacheBase = cacheBase;
_brandRepository = brandRepository;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_accessControlConfig = accessControlConfig;
}
@@ -39,7 +39,7 @@ public class BrandService : IBrandService
#region Fields
private readonly IRepository<Brand> _brandRepository;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
private readonly ICacheBase _cacheBase;
private readonly AccessControlConfig _accessControlConfig;
@@ -77,7 +77,7 @@ public class BrandService : IBrandService
if (!showHidden && !_accessControlConfig.IgnoreAcl)
{
//Limited to customer groups rules
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs
index d89616dc6..3ca6ab0d3 100644
--- a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs
@@ -32,14 +32,14 @@ public class CategoryService : ICategoryService
/// <param name="accessControlConfig"></param>
public CategoryService(ICacheBase cacheBase,
IRepository<Category> categoryRepository,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator,
IAclService aclService,
AccessControlConfig accessControlConfig)
{
_cacheBase = cacheBase;
_categoryRepository = categoryRepository;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_aclService = aclService;
_accessControlConfig = accessControlConfig;
@@ -50,7 +50,7 @@ public class CategoryService : ICategoryService
#region Fields
private readonly IRepository<Category> _categoryRepository;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
private readonly ICacheBase _cacheBase;
private readonly IAclService _aclService;
@@ -91,7 +91,7 @@ public class CategoryService : ICategoryService
if (!showHidden && !_accessControlConfig.IgnoreAcl)
{
//Limited to customer group (access control list)
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -124,12 +124,12 @@ public class CategoryService : ICategoryService
switch (_accessControlConfig.IgnoreAcl)
{
case true when
- string.IsNullOrEmpty(_workContext.CurrentStore.Id) || _accessControlConfig.IgnoreStoreLimitations:
+ string.IsNullOrEmpty(_workContextAccessor.WorkContext.CurrentStore.Id) || _accessControlConfig.IgnoreStoreLimitations:
return await Task.FromResult(query.ToList());
case false:
{
//Limited to customer group (access control list)
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -137,10 +137,10 @@ public class CategoryService : ICategoryService
}
}
- if (!string.IsNullOrEmpty(_workContext.CurrentStore.Id) && !_accessControlConfig.IgnoreStoreLimitations)
+ if (!string.IsNullOrEmpty(_workContextAccessor.WorkContext.CurrentStore.Id) && !_accessControlConfig.IgnoreStoreLimitations)
//Limited to stores rule
query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)
+ where !p.LimitedToStores || p.Stores.Contains(_workContextAccessor.WorkContext.CurrentStore.Id)
select p;
return await Task.FromResult(query.ToList());
}
@@ -155,8 +155,8 @@ public class CategoryService : ICategoryService
public virtual async Task<IList<Category>> GetAllCategoriesByParentCategoryId(string parentCategoryId = "",
bool showHidden = false, bool includeAllLevels = false)
{
- var storeId = _workContext.CurrentStore.Id;
- var customer = _workContext.CurrentCustomer;
+ var storeId = _workContextAccessor.WorkContext.CurrentStore.Id;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var key = string.Format(CacheKey.CATEGORIES_BY_PARENT_CATEGORY_ID_KEY, parentCategoryId, showHidden,
customer.Id, storeId, includeAllLevels);
return await _cacheBase.GetAsync(key, async () =>
@@ -170,7 +170,7 @@ public class CategoryService : ICategoryService
if (!_accessControlConfig.IgnoreAcl)
{
//Limited to customer groups rules
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -207,8 +207,8 @@ public class CategoryService : ICategoryService
var categories = await Task.FromResult(query.ToList());
if (!showHidden)
categories = categories
- .Where(c => _aclService.Authorize(c, _workContext.CurrentCustomer) &&
- _aclService.Authorize(c, _workContext.CurrentStore.Id))
+ .Where(c => _aclService.Authorize(c, _workContextAccessor.WorkContext.CurrentCustomer) &&
+ _aclService.Authorize(c, _workContextAccessor.WorkContext.CurrentStore.Id))
.ToList();
return categories;
@@ -228,8 +228,8 @@ public class CategoryService : ICategoryService
var categories = await Task.FromResult(query.ToList());
if (!showHidden)
categories = categories
- .Where(c => _aclService.Authorize(c, _workContext.CurrentCustomer) &&
- _aclService.Authorize(c, _workContext.CurrentStore.Id))
+ .Where(c => _aclService.Authorize(c, _workContextAccessor.WorkContext.CurrentCustomer) &&
+ _aclService.Authorize(c, _workContextAccessor.WorkContext.CurrentStore.Id))
.ToList();
return categories;
}
@@ -245,8 +245,8 @@ public class CategoryService : ICategoryService
.OrderBy(x => x.SearchBoxDisplayOrder);
var categories = (await Task.FromResult(query.ToList()))
- .Where(c => _aclService.Authorize(c, _workContext.CurrentCustomer) &&
- _aclService.Authorize(c, _workContext.CurrentStore.Id))
+ .Where(c => _aclService.Authorize(c, _workContextAccessor.WorkContext.CurrentCustomer) &&
+ _aclService.Authorize(c, _workContextAccessor.WorkContext.CurrentStore.Id))
.ToList();
return categories;
@@ -268,8 +268,8 @@ public class CategoryService : ICategoryService
while (category != null && //not null
(showHidden || category.Published) && //published
(showHidden ||
- _aclService.Authorize(category, _workContext.CurrentCustomer)) && //limited to customer groups
- (showHidden || _aclService.Authorize(category, _workContext.CurrentStore.Id)) && //limited to store
+ _aclService.Authorize(category, _workContextAccessor.WorkContext.CurrentCustomer)) && //limited to customer groups
+ (showHidden || _aclService.Authorize(category, _workContextAccessor.WorkContext.CurrentStore.Id)) && //limited to store
!alreadyProcessedCategoryIds.Contains(category.Id))
{
result.Add(category);
@@ -301,8 +301,8 @@ public class CategoryService : ICategoryService
while (category != null && //not null
(showHidden || category.Published) && //published
(showHidden ||
- _aclService.Authorize(category, _workContext.CurrentCustomer)) && //limited to customer groups
- (showHidden || _aclService.Authorize(category, _workContext.CurrentStore.Id)) && //limited to store
+ _aclService.Authorize(category, _workContextAccessor.WorkContext.CurrentCustomer)) && //limited to customer groups
+ (showHidden || _aclService.Authorize(category, _workContextAccessor.WorkContext.CurrentStore.Id)) && //limited to store
!alreadyProcessedCategoryIds.Contains(category.Id)) //avoid circular references
{
result.Add(category);
diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs
index d0b7571e8..e037f1350 100644
--- a/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs
@@ -19,17 +19,17 @@ public class ProductCategoryService : IProductCategoryService
private readonly ICacheBase _cacheBase;
private readonly IMediator _mediator;
private readonly IRepository<Product> _productRepository;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public ProductCategoryService(
IRepository<Product> productRepository,
ICacheBase cacheBase,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator, AccessControlConfig accessControlConfig)
{
_productRepository = productRepository;
_cacheBase = cacheBase;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_accessControlConfig = accessControlConfig;
}
@@ -49,7 +49,7 @@ public class ProductCategoryService : IProductCategoryService
return new PagedList<ProductsCategory>(new List<ProductsCategory>(), pageIndex, pageSize);
var key = string.Format(CacheKey.PRODUCTCATEGORIES_ALLBYCATEGORYID_KEY, showHidden, categoryId, pageIndex,
- pageSize, _workContext.CurrentCustomer.Id, _workContext.CurrentStore.Id);
+ pageSize, _workContextAccessor.WorkContext.CurrentCustomer.Id, _workContextAccessor.WorkContext.CurrentStore.Id);
return await _cacheBase.GetAsync(key, () =>
{
var query = _productRepository.Table.Where(x => x.ProductCategories.Any(y => y.CategoryId == categoryId));
@@ -59,7 +59,7 @@ public class ProductCategoryService : IProductCategoryService
if (!_accessControlConfig.IgnoreAcl)
{
//Limited to customer groups
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -68,7 +68,7 @@ public class ProductCategoryService : IProductCategoryService
if (!_accessControlConfig.IgnoreStoreLimitations)
{
//Limited to stores
- var currentStoreId = _workContext.CurrentStore.Id;
+ var currentStoreId = _workContextAccessor.WorkContext.CurrentStore.Id;
query = from p in query
where !p.LimitedToStores || p.Stores.Contains(currentStoreId)
select p;
diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs
index bda6e8f51..f1c97314a 100644
--- a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs
@@ -25,13 +25,13 @@ public class CollectionService : ICollectionService
/// </summary>
public CollectionService(ICacheBase cacheBase,
IRepository<Collection> collectionRepository,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator,
IAclService aclService, AccessControlConfig accessControlConfig)
{
_cacheBase = cacheBase;
_collectionRepository = collectionRepository;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_aclService = aclService;
_accessControlConfig = accessControlConfig;
@@ -42,7 +42,7 @@ public class CollectionService : ICollectionService
#region Fields
private readonly IRepository<Collection> _collectionRepository;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
private readonly ICacheBase _cacheBase;
private readonly IAclService _aclService;
@@ -81,7 +81,7 @@ public class CollectionService : ICollectionService
if (!showHidden && !_accessControlConfig.IgnoreAcl)
{
//Limited to customer groups rules
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -112,8 +112,8 @@ public class CollectionService : ICollectionService
var collections = await Task.FromResult(query.ToList());
if (!showHidden)
collections = collections
- .Where(c => _aclService.Authorize(c, _workContext.CurrentCustomer) &&
- _aclService.Authorize(c, _workContext.CurrentStore.Id))
+ .Where(c => _aclService.Authorize(c, _workContextAccessor.WorkContext.CurrentCustomer) &&
+ _aclService.Authorize(c, _workContextAccessor.WorkContext.CurrentStore.Id))
.ToList();
return collections;
}
diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs
index 21659c113..bd8603628 100644
--- a/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs
@@ -19,12 +19,12 @@ public class ProductCollectionService : IProductCollectionService
public ProductCollectionService(ICacheBase cacheBase,
IRepository<Product> productRepository,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator, AccessControlConfig accessControlConfig)
{
_cacheBase = cacheBase;
_productRepository = productRepository;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_accessControlConfig = accessControlConfig;
}
@@ -45,7 +45,7 @@ public class ProductCollectionService : IProductCollectionService
int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false)
{
var key = string.Format(CacheKey.PRODUCTCOLLECTIONS_ALLBYCOLLECTIONID_KEY, showHidden, collectionId, pageIndex,
- pageSize, _workContext.CurrentCustomer.Id, storeId);
+ pageSize, _workContextAccessor.WorkContext.CurrentCustomer.Id, storeId);
return await _cacheBase.GetAsync(key, () =>
{
var query = _productRepository.Table.Where(x =>
@@ -56,7 +56,7 @@ public class ProductCollectionService : IProductCollectionService
if (!_accessControlConfig.IgnoreAcl)
{
//ACL (access control list)
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -149,7 +149,7 @@ public class ProductCollectionService : IProductCollectionService
#region Fields
private readonly IRepository<Product> _productRepository;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
private readonly ICacheBase _cacheBase;
private readonly AccessControlConfig _accessControlConfig;
diff --git a/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.cs b/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.cs
index e30b74250..14cc54ac0 100644
--- a/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.cs
@@ -12,15 +12,15 @@ public class PriceFormatter : IPriceFormatter
{
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
#endregion
#region Constructors
- public PriceFormatter(IWorkContext workContext)
+ public PriceFormatter(IWorkContextAccessor workContextAccessor)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
#endregion
@@ -73,7 +73,7 @@ public class PriceFormatter : IPriceFormatter
/// <returns>Price</returns>
public virtual string FormatPrice(double price)
{
- return FormatPrice(price, _workContext.WorkingCurrency);
+ return FormatPrice(price, _workContextAccessor.WorkContext.WorkingCurrency);
}
/// <summary>
diff --git a/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs b/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs
index b592bf9ad..85fd416b6 100644
--- a/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs
@@ -28,7 +28,7 @@ public class PricingService : IPricingService
{
#region Ctor
- public PricingService(IWorkContext workContext,
+ public PricingService(IWorkContextAccessor workContextAccessor,
IDiscountService discountService,
ICategoryService categoryService,
IBrandService brandService,
@@ -40,7 +40,7 @@ public class PricingService : IPricingService
ShoppingCartSettings shoppingCartSettings,
CatalogSettings catalogSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_discountService = discountService;
_categoryService = categoryService;
_brandService = brandService;
@@ -70,7 +70,7 @@ public class PricingService : IPricingService
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IDiscountService _discountService;
private readonly ICategoryService _categoryService;
private readonly IBrandService _brandService;
@@ -529,9 +529,9 @@ public class PricingService : IPricingService
ArgumentNullException.ThrowIfNull(shoppingCartItem);
return await GetUnitPrice(product,
- _workContext.CurrentCustomer,
- _workContext.CurrentStore,
- _workContext.WorkingCurrency,
+ _workContextAccessor.WorkContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.CurrentStore,
+ _workContextAccessor.WorkContext.WorkingCurrency,
shoppingCartItem.ShoppingCartTypeId,
shoppingCartItem.Quantity,
shoppingCartItem.Attributes,
@@ -772,7 +772,7 @@ public class PricingService : IPricingService
if (adjustment > 0)
adjustment =
await _currencyService.ConvertFromPrimaryStoreCurrency(adjustment,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
}
break;
case AttributeValueType.AssociatedToProduct:
@@ -781,9 +781,9 @@ public class PricingService : IPricingService
var associatedProduct = await _productService.GetProductById(value.AssociatedProductId);
if (associatedProduct != null)
adjustment = (await GetFinalPrice(associatedProduct,
- _workContext.CurrentCustomer,
- _workContext.CurrentStore,
- _workContext.WorkingCurrency,
+ _workContextAccessor.WorkContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.CurrentStore,
+ _workContextAccessor.WorkContext.WorkingCurrency,
value.PriceAdjustment)).finalPrice * value.Quantity;
}
break;
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs
index a103dcb20..94b18de55 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs
@@ -22,16 +22,16 @@ public class ProductAttributeFormatter : IProductAttributeFormatter
private readonly IProductAttributeService _productAttributeService;
private readonly IProductService _productService;
private readonly ITaxService _taxService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public ProductAttributeFormatter(IWorkContext workContext,
+ public ProductAttributeFormatter(IWorkContextAccessor workContextAccessor,
IProductAttributeService productAttributeService,
ITaxService taxService,
IPriceFormatter priceFormatter,
IPricingService priceCalculationService,
IProductService productService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_productAttributeService = productAttributeService;
_taxService = taxService;
_priceFormatter = priceFormatter;
@@ -47,7 +47,7 @@ public class ProductAttributeFormatter : IProductAttributeFormatter
/// <returns>Attributes</returns>
public virtual Task<string> FormatAttributes(Product product, IList<CustomAttribute> customAttributes)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
return FormatAttributes(product, customAttributes, customer);
}
@@ -75,8 +75,8 @@ public class ProductAttributeFormatter : IProductAttributeFormatter
if (customAttributes == null || !customAttributes.Any())
return result.ToString();
- var langId = _workContext.WorkingLanguage != null
- ? _workContext.WorkingLanguage.Id
+ var langId = _workContextAccessor.WorkContext.WorkingLanguage != null
+ ? _workContextAccessor.WorkContext.WorkingLanguage.Id
: customer?.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId);
if (string.IsNullOrEmpty(langId))
@@ -195,7 +195,7 @@ public class ProductAttributeFormatter : IProductAttributeFormatter
if (allowHyperlinks)
{
var downloadLink =
- $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";
+ $"{_workContextAccessor.WorkContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";
attributeText =
$"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, langId)}</a>";
}
@@ -235,20 +235,20 @@ public class ProductAttributeFormatter : IProductAttributeFormatter
var attributeValuePriceAdjustment =
await _pricingService.GetProductAttributeValuePriceAdjustment(attributeValue);
var (priceAdjustmentBase, _) = await _taxService.GetProductPrice(product,
- attributeValuePriceAdjustment, _workContext.CurrentCustomer);
+ attributeValuePriceAdjustment, _workContextAccessor.WorkContext.CurrentCustomer);
switch (priceAdjustmentBase)
{
case > 0:
{
var priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustmentBase,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
formattedAttribute += $" [+{priceAdjustmentStr}]";
break;
}
case < 0:
{
var priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustmentBase,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
formattedAttribute += $" [-{priceAdjustmentStr}]";
break;
}
diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs
index 0e5994c76..579a5d067 100644
--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs
@@ -28,14 +28,14 @@ public class ProductService : IProductService
/// </summary>
public ProductService(ICacheBase cacheBase,
IRepository<Product> productRepository,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator,
IAclService aclService
)
{
_cacheBase = cacheBase;
_productRepository = productRepository;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_aclService = aclService;
}
@@ -46,7 +46,7 @@ public class ProductService : IProductService
private readonly IRepository<Product> _productRepository;
private readonly ICacheBase _cacheBase;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IAclService _aclService;
private readonly IMediator _mediator;
@@ -130,8 +130,8 @@ public class ProductService : IProductService
foreach (var id in productIds)
{
var product = await GetProductById(id);
- if (product != null && (showHidden || (_aclService.Authorize(product, _workContext.CurrentCustomer) &&
- _aclService.Authorize(product, _workContext.CurrentStore.Id) &&
+ if (product != null && (showHidden || (_aclService.Authorize(product, _workContextAccessor.WorkContext.CurrentCustomer) &&
+ _aclService.Authorize(product, _workContextAccessor.WorkContext.CurrentStore.Id) &&
product.IsAvailable())))
products.Add(product);
}
@@ -524,7 +524,7 @@ public class ProductService : IProductService
bool? overridePublished = null)
{
var model = await _mediator.Send(new GetSearchProductsQuery {
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
LoadFilterableSpecificationAttributeOptionIds = loadFilterableSpecificationAttributeOptionIds,
PageIndex = pageIndex,
PageSize = pageSize,
@@ -608,7 +608,7 @@ public class ProductService : IProductService
//ACL mapping
if (!showHidden)
- products = products.Where(x => _aclService.Authorize(x, _workContext.CurrentCustomer)).ToList();
+ products = products.Where(x => _aclService.Authorize(x, _workContextAccessor.WorkContext.CurrentCustomer)).ToList();
//Store acl
if (!showHidden && !string.IsNullOrEmpty(storeId))
products = products.Where(x => _aclService.Authorize(x, storeId)).ToList();
@@ -895,8 +895,8 @@ public class ProductService : IProductService
var productToAdd = await GetProductById(crossSell);
//validate product
if (productToAdd is not { Published: true }
- || !_aclService.Authorize(productToAdd, _workContext.CurrentCustomer) ||
- !_aclService.Authorize(productToAdd, _workContext.CurrentStore.Id)
+ || !_aclService.Authorize(productToAdd, _workContextAccessor.WorkContext.CurrentCustomer) ||
+ !_aclService.Authorize(productToAdd, _workContextAccessor.WorkContext.CurrentStore.Id)
|| !productToAdd.IsAvailable())
continue;
diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs
index 92c6690dc..e4150017b 100644
--- a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs
@@ -22,7 +22,7 @@ public class TaxService : ITaxService
#region Ctor
public TaxService(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
ICountryService countryService,
IEnumerable<ITaxProvider> taxProviders,
@@ -32,7 +32,7 @@ public class TaxService : ITaxService
CustomerSettings customerSettings,
AddressSettings addressSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_taxSettings = taxSettings;
_taxProviderSettings = taxProviderSettings;
@@ -47,7 +47,7 @@ public class TaxService : ITaxService
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
private readonly ICountryService _countryService;
private readonly IEnumerable<ITaxProvider> _taxProviders;
@@ -240,7 +240,7 @@ public class TaxService : ITaxService
public virtual ITaxProvider LoadActiveTaxProvider()
{
var taxProvider = LoadTaxProviderBySystemName(_taxProviderSettings.ActiveTaxProviderSystemName) ??
- LoadAllTaxProviders(_workContext.CurrentCustomer, _workContext.CurrentStore.Id)
+ LoadAllTaxProviders(_workContextAccessor.WorkContext.CurrentCustomer, _workContextAccessor.WorkContext.CurrentStore.Id)
.FirstOrDefault();
return taxProvider;
}
@@ -279,7 +279,7 @@ public class TaxService : ITaxService
/// <returns>Price</returns>
public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
return await GetProductPrice(product, price, customer);
}
@@ -293,7 +293,7 @@ public class TaxService : ITaxService
public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, double price,
Customer customer)
{
- var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
+ var includingTax = _workContextAccessor.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax;
return await GetProductPrice(product, price, includingTax, customer);
}
@@ -469,7 +469,7 @@ public class TaxService : ITaxService
/// <returns>Price</returns>
public virtual async Task<(double shippingPrice, double taxRate)> GetShippingPrice(double price, Customer customer)
{
- var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
+ var includingTax = _workContextAccessor.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax;
return await GetShippingPrice(price, includingTax, customer);
}
@@ -501,7 +501,7 @@ public class TaxService : ITaxService
public virtual async Task<(double paymentPrice, double taxRate)> GetPaymentMethodAdditionalFee(double price,
Customer customer)
{
- var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
+ var includingTax = _workContextAccessor.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax;
return await GetPaymentMethodAdditionalFee(price, includingTax, customer);
}
@@ -532,7 +532,7 @@ public class TaxService : ITaxService
public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca,
CheckoutAttributeValue cav)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
return await GetCheckoutAttributePrice(ca, cav, customer);
}
@@ -546,7 +546,7 @@ public class TaxService : ITaxService
public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca,
CheckoutAttributeValue cav, Customer customer)
{
- var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
+ var includingTax = _workContextAccessor.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax;
return await GetCheckoutAttributePrice(ca, cav, includingTax, customer);
}
diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderNotificationCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderNotificationCommandHandler.cs
new file mode 100644
index 000000000..95206a61a
--- /dev/null
+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderNotificationCommandHandler.cs
@@ -0,0 +1,105 @@
+using Grand.Business.Core.Commands.Messages.Common;
+using Grand.Business.Core.Interfaces.Checkout.Orders;
+using Grand.Business.Core.Interfaces.Common.Pdf;
+using Grand.Business.Core.Interfaces.Messages;
+using Grand.Business.Core.Queries.Checkout.Orders;
+using Grand.Domain.Localization;
+using Grand.Domain.Orders;
+using MediatR;
+using Microsoft.Extensions.Logging;
+
+namespace Grand.Business.Checkout.Commands.Handlers.Orders;
+
+public class OrderNotificationCommandHandler : IRequestHandler<OrderNotificationCommand>
+{
+ private readonly IOrderService _orderService;
+ private readonly IMessageProviderService _messageProviderService;
+ private readonly OrderSettings _orderSettings;
+ private readonly LanguageSettings _languageSettings;
+ private readonly IPdfService _pdfService;
+ private readonly ILogger<OrderNotificationCommandHandler> _logger;
+ private readonly IMediator _mediator;
+
+ public OrderNotificationCommandHandler(
+ IOrderService orderService,
+ IMessageProviderService messageProviderService,
+ OrderSettings orderSettings,
+ LanguageSettings languageSettings,
+ IPdfService pdfService,
+ ILogger<OrderNotificationCommandHandler> logger,
+ IMediator mediator)
+ {
+ _orderService = orderService;
+ _messageProviderService = messageProviderService;
+ _orderSettings = orderSettings;
+ _languageSettings = languageSettings;
+ _pdfService = pdfService;
+ _logger = logger;
+ _mediator = mediator;
+ }
+
+ public async Task Handle(OrderNotificationCommand request, CancellationToken cancellationToken)
+ {
+
+ try
+ {
+ if (request.WorkContext.OriginalCustomerIfImpersonated != null)
+ //this order is placed by a store administrator impersonating a customer
+ await _orderService.InsertOrderNote(new OrderNote {
+ Note =
+ $"Order placed by a store owner ('{request.WorkContext.OriginalCustomerIfImpersonated.Email}'. ID = {request.WorkContext.OriginalCustomerIfImpersonated.Id}) impersonating the customer.",
+ DisplayToCustomer = false,
+ OrderId = request.Order.Id
+ });
+ else
+ await _orderService.InsertOrderNote(new OrderNote {
+ Note = "Order placed",
+ DisplayToCustomer = false,
+ OrderId = request.Order.Id
+ });
+
+ //send email notifications
+ await _messageProviderService.SendOrderPlacedStoreOwnerMessage(request.Order, request.WorkContext.CurrentCustomer,
+ _languageSettings.DefaultAdminLanguageId);
+
+ string orderPlacedAttachmentFilePath = string.Empty, orderPlacedAttachmentFileName = string.Empty;
+ var orderPlacedAttachments = new List<string>();
+
+ try
+ {
+ orderPlacedAttachmentFilePath =
+ _orderSettings.AttachPdfInvoiceToOrderPlacedEmail && !_orderSettings.AttachPdfInvoiceToBinary
+ ? await _pdfService.PrintOrderToPdf(request.Order, request.Order.CustomerLanguageId)
+ : null;
+ orderPlacedAttachmentFileName =
+ _orderSettings.AttachPdfInvoiceToOrderPlacedEmail && !_orderSettings.AttachPdfInvoiceToBinary
+ ? "order.pdf"
+ : null;
+ orderPlacedAttachments = _orderSettings.AttachPdfInvoiceToOrderPlacedEmail &&
+ _orderSettings.AttachPdfInvoiceToBinary
+ ? [
+ await _pdfService.SaveOrderToBinary(request.Order, request.Order.CustomerLanguageId)
+ ]
+ : [];
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error - order placed attachment file {OrderOrderNumber}", request.Order.OrderNumber);
+ }
+
+ await _messageProviderService.SendOrderPlacedCustomerMessage(request.Order, request.WorkContext.CurrentCustomer, request.Order.CustomerLanguageId, orderPlacedAttachmentFilePath, orderPlacedAttachmentFileName, orderPlacedAttachments);
+
+ if (request.Order.OrderItems.Any(x => !string.IsNullOrEmpty(x.VendorId)))
+ {
+ var vendors = await _mediator.Send(new GetVendorsInOrderQuery { Order = request.Order });
+ foreach (var vendor in vendors)
+ await _messageProviderService.SendOrderPlacedVendorMessage(request.Order, request.WorkContext.CurrentCustomer, vendor,
+ _languageSettings.DefaultAdminLanguageId);
+ }
+ }
+ catch (Exception e)
+ {
+ _logger.LogError(e, "Place order send notification error");
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs
index 7164dabe8..3b844d957 100644
--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs
+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs
@@ -1,4 +1,5 @@
using Grand.Business.Core.Commands.Checkout.Orders;
+using Grand.Business.Core.Commands.Messages.Common;
using Grand.Business.Core.Events.Checkout.Orders;
using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Catalog.Discounts;
@@ -11,7 +12,6 @@ using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Business.Core.Interfaces.Common.Pdf;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.Core.Queries.Checkout.Orders;
@@ -20,7 +20,6 @@ using Grand.Domain.Catalog;
using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Domain.Discounts;
-using Grand.Domain.Localization;
using Grand.Domain.Orders;
using Grand.Domain.Payments;
using Grand.Domain.Shipping;
@@ -29,7 +28,6 @@ using Grand.Infrastructure;
using Grand.SharedKernel;
using Grand.SharedKernel.Extensions;
using MediatR;
-using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Grand.Business.Checkout.Commands.Handlers.Orders;
@@ -61,14 +59,13 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
private readonly IProductReservationService _productReservationService;
private readonly IProductService _productService;
private readonly ISalesEmployeeService _salesEmployeeService;
- private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly ShippingSettings _shippingSettings;
private readonly ShoppingCartSettings _shoppingCartSettings;
private readonly IShoppingCartValidator _shoppingCartValidator;
private readonly ITaxService _taxService;
private readonly TaxSettings _taxSettings;
private readonly IVendorService _vendorService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public PlaceOrderCommandHandler(
IOrderService orderService,
@@ -86,7 +83,7 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
ITaxService taxService,
ICustomerService customerService,
IDiscountService discountService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
IMessageProviderService messageProviderService,
IVendorService vendorService,
@@ -98,7 +95,6 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
IAuctionService auctionService,
ICountryService countryService,
IShoppingCartValidator shoppingCartValidator,
- IServiceScopeFactory serviceScopeFactory,
ShippingSettings shippingSettings,
ShoppingCartSettings shoppingCartSettings,
PaymentSettings paymentSettings,
@@ -121,7 +117,7 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
_customerService = customerService;
_groupService = groupService;
_discountService = discountService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_messageProviderService = messageProviderService;
_vendorService = vendorService;
_salesEmployeeService = salesEmployeeService;
@@ -132,7 +128,6 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
_auctionService = auctionService;
_countryService = countryService;
_shoppingCartValidator = shoppingCartValidator;
- _serviceScopeFactory = serviceScopeFactory;
_shippingSettings = shippingSettings;
_shoppingCartSettings = shoppingCartSettings;
_paymentSettings = paymentSettings;
@@ -182,9 +177,7 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
#region Events & notes
- _ = Task.Run(
- () => SendNotification(_serviceScopeFactory, result.PlacedOrder, _workContext.CurrentCustomer,
- _workContext.OriginalCustomerIfImpersonated), cancellationToken);
+ await _mediator.Send(new OrderNotificationCommand { Order = result.PlacedOrder, WorkContext = _workContextAccessor.WorkContext }, cancellationToken);
//check order status
await _mediator.Send(new CheckOrderStatusCommand { Order = result.PlacedOrder }, cancellationToken);
@@ -273,7 +266,7 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
var paymentTransaction = new PaymentTransaction();
var paymentTransactionId =
details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PaymentTransaction,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
if (!string.IsNullOrEmpty(paymentTransactionId))
{
paymentTransaction = await _paymentTransactionService.GetById(paymentTransactionId);
@@ -291,7 +284,7 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
paymentTransaction.OrderGuid =
paymentTransaction.OrderGuid == Guid.Empty ? Guid.NewGuid() : paymentTransaction.OrderGuid;
paymentTransaction.PaymentMethodSystemName = details.PaymentMethodSystemName;
- paymentTransaction.StoreId = _workContext.CurrentStore.Id;
+ paymentTransaction.StoreId = _workContextAccessor.WorkContext.CurrentStore.Id;
paymentTransaction.CustomerId = details.Customer.Id;
paymentTransaction.TransactionAmount = details.OrderTotal;
paymentTransaction.CurrencyRate = details.CurrencyRate;
@@ -359,19 +352,19 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
switch (attributeValue.AttributeValueTypeId)
{
case AttributeValueType.Simple:
- {
- //simple attribute
- attributesTotalWeight += attributeValue.WeightAdjustment;
- }
+ {
+ //simple attribute
+ attributesTotalWeight += attributeValue.WeightAdjustment;
+ }
break;
case AttributeValueType.AssociatedToProduct:
- {
- //bundled product
- var associatedProduct =
- await _productService.GetProductById(attributeValue.AssociatedProductId);
- if (associatedProduct is { IsShipEnabled: true })
- attributesTotalWeight += associatedProduct.Weight * attributeValue.Quantity;
- }
+ {
+ //bundled product
+ var associatedProduct =
+ await _productService.GetProductById(attributeValue.AssociatedProductId);
+ if (associatedProduct is { IsShipEnabled: true })
+ attributesTotalWeight += associatedProduct.Weight * attributeValue.Quantity;
+ }
break;
}
}
@@ -384,7 +377,7 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
{
var details = new PlaceOrderContainer {
//customer
- Customer = _workContext.CurrentCustomer
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer
};
if (details.Customer == null)
throw new ArgumentException("Customer is not set");
@@ -411,8 +404,8 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
//customer currency
var currencyTmp = await _currencyService.GetCurrencyById(
details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CurrencyId,
- _workContext.CurrentStore.Id));
- var customerCurrency = currencyTmp is { Published: true } ? currencyTmp : _workContext.WorkingCurrency;
+ _workContextAccessor.WorkContext.CurrentStore.Id));
+ var customerCurrency = currencyTmp is { Published: true } ? currencyTmp : _workContextAccessor.WorkContext.WorkingCurrency;
details.Currency = customerCurrency;
var primaryStoreCurrency = await _currencyService.GetPrimaryStoreCurrency();
details.CurrencyRate = Math.Round(customerCurrency.Rate / primaryStoreCurrency.Rate, 6);
@@ -421,10 +414,10 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
//customer language
details.Language = await _languageService.GetLanguageById(
details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId,
- _workContext.CurrentStore.Id));
+ _workContextAccessor.WorkContext.CurrentStore.Id));
if (details.Language is not { Published: true })
- details.Language = _workContext.WorkingLanguage;
+ details.Language = _workContextAccessor.WorkContext.WorkingLanguage;
details.BillingAddress = details.Customer.BillingAddress;
if (!string.IsNullOrEmpty(details.BillingAddress.CountryId))
@@ -437,14 +430,14 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
//checkout attributes
details.CheckoutAttributes =
details.Customer.GetUserFieldFromEntity<List<CustomAttribute>>(SystemCustomerFieldNames.CheckoutAttributes,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
details.CheckoutAttributeDescription =
await _checkoutAttributeFormatter.FormatAttributes(details.CheckoutAttributes, details.Customer);
//load and validate customer shopping cart
details.Cart = details.Customer.ShoppingCartItems
.Where(sci => sci.ShoppingCartTypeId is ShoppingCartType.ShoppingCart or ShoppingCartType.Auctions)
- .LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, _workContext.CurrentStore.Id)
+ .LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, _workContextAccessor.WorkContext.CurrentStore.Id)
.ToList();
if (!details.Cart.Any())
@@ -484,7 +477,7 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
if (_taxSettings.AllowCustomersToSelectTaxDisplayType)
details.TaxDisplayType =
(TaxDisplayType)details.Customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.TaxDisplayTypeId,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
else
details.TaxDisplayType = _taxSettings.TaxDisplayType;
@@ -517,7 +510,7 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
{
var pickupPoint =
details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.SelectedPickupPoint,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
if (_shippingSettings.AllowPickUpInStore && pickupPoint != null)
{
details.PickUpInStore = true;
@@ -543,7 +536,7 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
var shippingOption =
details.Customer.GetUserFieldFromEntity<ShippingOption>(SystemCustomerFieldNames.SelectedShippingOption,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
if (shippingOption != null)
{
details.ShippingMethodName = shippingOption.Name;
@@ -573,8 +566,8 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
//payment
var paymentMethodSystemName =
- _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.SelectedPaymentMethod,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.SelectedPaymentMethod,
+ _workContextAccessor.WorkContext.CurrentStore.Id);
details.PaymentMethodSystemName = paymentMethodSystemName;
var paymentAdditionalFee =
await _paymentService.GetAdditionalHandlingFee(details.Cart, paymentMethodSystemName);
@@ -644,7 +637,7 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
var itemWeight = await GetShoppingCartItemWeight(sc);
var warehouseId = !string.IsNullOrEmpty(sc.WarehouseId)
? sc.WarehouseId
- : _workContext.CurrentStore.DefaultWarehouseId;
+ : _workContextAccessor.WorkContext.CurrentStore.DefaultWarehouseId;
if (!product.UseMultipleWarehouses && string.IsNullOrEmpty(warehouseId))
if (!string.IsNullOrEmpty(product.WarehouseId))
warehouseId = product.WarehouseId;
@@ -741,7 +734,7 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
SenderEmail = giftVoucherSenderEmail,
Message = giftVoucherMessage,
IsRecipientNotified = false,
- StoreId = _orderSettings.GiftVouchers_Assign_StoreId ? _workContext.CurrentStore.Id : string.Empty
+ StoreId = _orderSettings.GiftVouchers_Assign_StoreId ? _workContextAccessor.WorkContext.CurrentStore.Id : string.Empty
};
await _giftVoucherService.InsertGiftVoucher(gc);
}
@@ -1030,93 +1023,4 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
return order;
}
-
- /// <summary>
- /// Send notification order
- /// </summary>
- /// <param name="scopeFactory"></param>
- /// <param name="order">Order</param>
- /// <param name="customer"></param>
- /// <param name="originalCustomerIfImpersonated"></param>
- protected virtual async Task SendNotification(IServiceScopeFactory scopeFactory, Order order, Customer customer,
- Customer originalCustomerIfImpersonated)
- {
- using var scope = scopeFactory.CreateScope();
-
- var workContext = scope.ServiceProvider.GetService<IWorkContextSetter>();
- await workContext.SetCurrentCustomer(customer);
- await workContext.SetWorkingLanguage(customer);
- await workContext.SetWorkingCurrency(customer);
- await workContext.SetTaxDisplayType(customer);
-
- var orderService = scope.ServiceProvider.GetRequiredService<IOrderService>();
- var messageProviderService = scope.ServiceProvider.GetRequiredService<IMessageProviderService>();
- var orderSettings = scope.ServiceProvider.GetRequiredService<OrderSettings>();
- var languageSettings = scope.ServiceProvider.GetRequiredService<LanguageSettings>();
- var pdfService = scope.ServiceProvider.GetRequiredService<IPdfService>();
- var mediator = scope.ServiceProvider.GetRequiredService<IMediator>();
- try
- {
- //notes, messages
- if (originalCustomerIfImpersonated != null)
- //this order is placed by a store administrator impersonating a customer
- await orderService.InsertOrderNote(new OrderNote {
- Note =
- $"Order placed by a store owner ('{originalCustomerIfImpersonated.Email}'. ID = {originalCustomerIfImpersonated.Id}) impersonating the customer.",
- DisplayToCustomer = false,
- OrderId = order.Id
- });
- else
- await orderService.InsertOrderNote(new OrderNote {
- Note = "Order placed",
- DisplayToCustomer = false,
- OrderId = order.Id
- });
-
- //send email notifications
- await messageProviderService.SendOrderPlacedStoreOwnerMessage(order, customer,
- languageSettings.DefaultAdminLanguageId);
-
- string orderPlacedAttachmentFilePath = string.Empty, orderPlacedAttachmentFileName = string.Empty;
- var orderPlacedAttachments = new List<string>();
-
- try
- {
- orderPlacedAttachmentFilePath =
- orderSettings.AttachPdfInvoiceToOrderPlacedEmail && !orderSettings.AttachPdfInvoiceToBinary
- ? await pdfService.PrintOrderToPdf(order, order.CustomerLanguageId)
- : null;
- orderPlacedAttachmentFileName =
- orderSettings.AttachPdfInvoiceToOrderPlacedEmail && !orderSettings.AttachPdfInvoiceToBinary
- ? "order.pdf"
- : null;
- orderPlacedAttachments = orderSettings.AttachPdfInvoiceToOrderPlacedEmail &&
- orderSettings.AttachPdfInvoiceToBinary
- ? [
- await pdfService.SaveOrderToBinary(order, order.CustomerLanguageId)
- ]
- : [];
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error - order placed attachment file {OrderOrderNumber}", order.OrderNumber);
- }
-
- await messageProviderService
- .SendOrderPlacedCustomerMessage(order, customer, order.CustomerLanguageId,
- orderPlacedAttachmentFilePath, orderPlacedAttachmentFileName, orderPlacedAttachments);
-
- if (order.OrderItems.Any(x => !string.IsNullOrEmpty(x.VendorId)))
- {
- var vendors = await mediator.Send(new GetVendorsInOrderQuery { Order = order });
- foreach (var vendor in vendors)
- await messageProviderService.SendOrderPlacedVendorMessage(order, customer, vendor,
- languageSettings.DefaultAdminLanguageId);
- }
- }
- catch (Exception e)
- {
- _logger.LogError(e, "Place order send notification error");
- }
- }
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Checkout/Events/ShoppingCart/CustomerLoggedInEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/ShoppingCart/CustomerLoggedInEventHandler.cs
index 7af975b52..f6590eb87 100644
--- a/src/Business/Grand.Business.Checkout/Events/ShoppingCart/CustomerLoggedInEventHandler.cs
+++ b/src/Business/Grand.Business.Checkout/Events/ShoppingCart/CustomerLoggedInEventHandler.cs
@@ -8,17 +8,17 @@ namespace Grand.Business.Checkout.Events.ShoppingCart;
public class CustomerLoggedInEventHandler : INotificationHandler<CustomerLoggedInEvent>
{
private readonly IShoppingCartService _shoppingCartService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public CustomerLoggedInEventHandler(IShoppingCartService shoppingCartService, IWorkContext workContext)
+ public CustomerLoggedInEventHandler(IShoppingCartService shoppingCartService, IWorkContextAccessor workContextAccessor)
{
_shoppingCartService = shoppingCartService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task Handle(CustomerLoggedInEvent notification, CancellationToken cancellationToken)
{
//migrate shopping cart
- await _shoppingCartService.MigrateShoppingCart(_workContext.CurrentCustomer, notification.Customer, true);
+ await _shoppingCartService.MigrateShoppingCart(_workContextAccessor.WorkContext.CurrentCustomer, notification.Customer, true);
}
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs
index 3b5c4e73f..5bde9ab5d 100644
--- a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs
+++ b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs
@@ -22,15 +22,15 @@ public class CheckoutAttributeFormatter : ICheckoutAttributeFormatter
private readonly ICurrencyService _currencyService;
private readonly IPriceFormatter _priceFormatter;
private readonly ITaxService _taxService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public CheckoutAttributeFormatter(IWorkContext workContext,
+ public CheckoutAttributeFormatter(IWorkContextAccessor workContextAccessor,
ICheckoutAttributeParser checkoutAttributeParser,
ICurrencyService currencyService,
ITaxService taxService,
IPriceFormatter priceFormatter)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_checkoutAttributeParser = checkoutAttributeParser;
_currencyService = currencyService;
_taxService = taxService;
@@ -76,7 +76,7 @@ public class CheckoutAttributeFormatter : ICheckoutAttributeFormatter
case AttributeControlType.MultilineTextbox:
{
//multiline text box
- var attributeName = attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);
+ var attributeName = attribute.GetTranslation(a => a.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id);
//encode (if required)
if (htmlEncode)
attributeName = WebUtility.HtmlEncode(attributeName);
@@ -91,14 +91,14 @@ public class CheckoutAttributeFormatter : ICheckoutAttributeFormatter
{
var attributeText = string.Empty;
var attributeName =
- attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);
+ attribute.GetTranslation(a => a.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id);
if (allowHyperlinks)
{
//hyperlinks are allowed
var downloadLink =
- $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";
+ $"{_workContextAccessor.WorkContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";
attributeText =
- $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, _workContext.WorkingLanguage.Id)}</a>";
+ $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, _workContextAccessor.WorkContext.WorkingLanguage.Id)}</a>";
}
formattedAttribute = $"{attributeName}: {attributeText}";
@@ -110,7 +110,7 @@ public class CheckoutAttributeFormatter : ICheckoutAttributeFormatter
{
//other attributes (text box, datepicker)
formattedAttribute =
- $"{attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id)}: {valueStr}";
+ $"{attribute.GetTranslation(a => a.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id)}: {valueStr}";
//encode (if required)
if (htmlEncode)
formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
@@ -124,7 +124,7 @@ public class CheckoutAttributeFormatter : ICheckoutAttributeFormatter
if (attributeValue != null)
{
formattedAttribute =
- $"{attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id)}: {attributeValue.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id)}";
+ $"{attribute.GetTranslation(a => a.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id)}: {attributeValue.GetTranslation(a => a.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id)}";
if (renderPrices)
{
var priceAdjustmentBase =
@@ -132,7 +132,7 @@ public class CheckoutAttributeFormatter : ICheckoutAttributeFormatter
.checkoutPrice;
var priceAdjustment =
await _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
if (priceAdjustmentBase > 0)
{
var priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment);
diff --git a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs
index cabec3e84..9499f0645 100644
--- a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs
+++ b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs
@@ -25,12 +25,12 @@ public class CheckoutAttributeService : ICheckoutAttributeService
ICacheBase cacheBase,
IRepository<CheckoutAttribute> checkoutAttributeRepository,
IMediator mediator,
- IWorkContext workContext, AccessControlConfig accessControlConfig)
+ IWorkContextAccessor workContextAccessor, AccessControlConfig accessControlConfig)
{
_cacheBase = cacheBase;
_checkoutAttributeRepository = checkoutAttributeRepository;
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_accessControlConfig = accessControlConfig;
}
@@ -41,7 +41,7 @@ public class CheckoutAttributeService : ICheckoutAttributeService
private readonly IRepository<CheckoutAttribute> _checkoutAttributeRepository;
private readonly IMediator _mediator;
private readonly ICacheBase _cacheBase;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly AccessControlConfig _accessControlConfig;
#endregion
@@ -71,7 +71,7 @@ public class CheckoutAttributeService : ICheckoutAttributeService
{
if (!ignoreAcl && !_accessControlConfig.IgnoreAcl)
{
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs
index 19251db11..7062e2772 100644
--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs
+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs
@@ -53,7 +53,7 @@ public class OrderCalculationService : IOrderCalculationService
/// <param name="shippingSettings">Shipping settings</param>
/// <param name="shoppingCartSettings">Shopping cart settings</param>
/// <param name="catalogSettings">Catalog settings</param>
- public OrderCalculationService(IWorkContext workContext,
+ public OrderCalculationService(IWorkContextAccessor workContextAccessor,
IPricingService priceCalculationService,
ITaxService taxService,
IShippingService shippingService,
@@ -72,7 +72,7 @@ public class OrderCalculationService : IOrderCalculationService
ShoppingCartSettings shoppingCartSettings,
CatalogSettings catalogSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_pricingService = priceCalculationService;
_taxService = taxService;
_shippingService = shippingService;
@@ -96,7 +96,7 @@ public class OrderCalculationService : IOrderCalculationService
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IPricingService _pricingService;
private readonly ITaxService _taxService;
private readonly IShippingService _shippingService;
@@ -136,7 +136,7 @@ public class OrderCalculationService : IOrderCalculationService
return (discountAmount, appliedDiscounts);
var allDiscounts = await _discountService.GetActiveDiscountsByContext(DiscountType.AssignedToOrderSubTotal,
- _workContext.CurrentStore.Id, currency.CurrencyCode);
+ _workContextAccessor.WorkContext.CurrentStore.Id, currency.CurrencyCode);
var allowedDiscounts = new List<ApplyDiscount>();
if (allDiscounts != null)
foreach (var discount in allDiscounts)
@@ -154,7 +154,7 @@ public class OrderCalculationService : IOrderCalculationService
}
var preferredDiscounts = await _discountService.GetPreferredDiscount(allowedDiscounts, customer,
- _workContext.WorkingCurrency, orderSubTotal);
+ _workContextAccessor.WorkContext.WorkingCurrency, orderSubTotal);
appliedDiscounts = preferredDiscounts.appliedDiscount;
discountAmount = preferredDiscounts.discountAmount;
@@ -181,7 +181,7 @@ public class OrderCalculationService : IOrderCalculationService
return (shippingDiscountAmount, appliedDiscounts);
var allDiscounts = await _discountService.GetActiveDiscountsByContext(DiscountType.AssignedToShipping,
- _workContext.CurrentStore.Id, currency.CurrencyCode);
+ _workContextAccessor.WorkContext.CurrentStore.Id, currency.CurrencyCode);
var allowedDiscounts = new List<ApplyDiscount>();
if (allDiscounts != null)
foreach (var discount in allDiscounts)
@@ -199,7 +199,7 @@ public class OrderCalculationService : IOrderCalculationService
}
var (appliedDiscount, discountAmount) = await _discountService.GetPreferredDiscount(allowedDiscounts,
- customer, _workContext.WorkingCurrency, shippingTotal);
+ customer, _workContextAccessor.WorkContext.WorkingCurrency, shippingTotal);
appliedDiscounts = appliedDiscount;
shippingDiscountAmount = discountAmount;
@@ -208,7 +208,7 @@ public class OrderCalculationService : IOrderCalculationService
if (_shoppingCartSettings.RoundPrices)
shippingDiscountAmount =
- RoundingHelper.RoundPrice(shippingDiscountAmount, _workContext.WorkingCurrency);
+ RoundingHelper.RoundPrice(shippingDiscountAmount, _workContextAccessor.WorkContext.WorkingCurrency);
return (shippingDiscountAmount, appliedDiscounts);
}
@@ -230,7 +230,7 @@ public class OrderCalculationService : IOrderCalculationService
return (discountAmount, appliedDiscounts);
var allDiscounts = await _discountService.GetActiveDiscountsByContext(DiscountType.AssignedToOrderTotal,
- _workContext.CurrentStore.Id, currency.CurrencyCode);
+ _workContextAccessor.WorkContext.CurrentStore.Id, currency.CurrencyCode);
var allowedDiscounts = new List<ApplyDiscount>();
if (allDiscounts != null)
foreach (var discount in allDiscounts)
@@ -248,7 +248,7 @@ public class OrderCalculationService : IOrderCalculationService
}
var preferredDiscount = await _discountService.GetPreferredDiscount(allowedDiscounts, customer,
- _workContext.WorkingCurrency, orderTotal);
+ _workContextAccessor.WorkContext.WorkingCurrency, orderTotal);
appliedDiscounts = preferredDiscount.appliedDiscount;
discountAmount = preferredDiscount.discountAmount;
@@ -256,7 +256,7 @@ public class OrderCalculationService : IOrderCalculationService
discountAmount = 0;
if (_shoppingCartSettings.RoundPrices)
- discountAmount = RoundingHelper.RoundPrice(discountAmount, _workContext.WorkingCurrency);
+ discountAmount = RoundingHelper.RoundPrice(discountAmount, _workContextAccessor.WorkContext.WorkingCurrency);
return (discountAmount, appliedDiscounts);
}
@@ -308,7 +308,7 @@ public class OrderCalculationService : IOrderCalculationService
return (discountAmount, appliedDiscounts, subTotalWithoutDiscount, subTotalWithDiscount, taxRates);
//get the customer
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
//sub totals
double subTotalExclTaxWithoutDiscount = 0;
@@ -344,7 +344,7 @@ public class OrderCalculationService : IOrderCalculationService
{
var checkoutAttributes =
customer.GetUserFieldFromEntity<List<CustomAttribute>>(SystemCustomerFieldNames.CheckoutAttributes,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
var attributeValues = await _checkoutAttributeParser.ParseCheckoutAttributeValue(checkoutAttributes);
foreach (var attributeValue in attributeValues)
{
@@ -353,14 +353,14 @@ public class OrderCalculationService : IOrderCalculationService
customer);
var caExclTax =
await _currencyService.ConvertFromPrimaryStoreCurrency(
- checkoutAttributePriceExclTax.checkoutPrice, _workContext.WorkingCurrency);
+ checkoutAttributePriceExclTax.checkoutPrice, _workContextAccessor.WorkContext.WorkingCurrency);
var (checkoutPrice, taxRate) =
await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, true,
customer);
var caInclTax =
await _currencyService.ConvertFromPrimaryStoreCurrency(checkoutPrice,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
subTotalExclTaxWithoutDiscount += caExclTax;
subTotalInclTaxWithoutDiscount += caInclTax;
@@ -383,12 +383,12 @@ public class OrderCalculationService : IOrderCalculationService
if (_shoppingCartSettings.RoundPrices)
subTotalWithoutDiscount =
- RoundingHelper.RoundPrice(subTotalWithoutDiscount, _workContext.WorkingCurrency);
+ RoundingHelper.RoundPrice(subTotalWithoutDiscount, _workContextAccessor.WorkContext.WorkingCurrency);
//We calculate discount amount on order subtotal excl tax (discount first)
//calculate discount amount ('Applied to order subtotal' discount)
- var orderSubtotalDiscount = await GetOrderSubtotalDiscount(customer, _workContext.CurrentStore,
- _workContext.WorkingCurrency, subTotalExclTaxWithoutDiscount);
+ var orderSubtotalDiscount = await GetOrderSubtotalDiscount(customer, _workContextAccessor.WorkContext.CurrentStore,
+ _workContextAccessor.WorkContext.WorkingCurrency, subTotalExclTaxWithoutDiscount);
var discountAmountExclTax = orderSubtotalDiscount.ordersubtotaldiscount;
appliedDiscounts = orderSubtotalDiscount.appliedDiscounts;
@@ -414,7 +414,7 @@ public class OrderCalculationService : IOrderCalculationService
discountAmountInclTax += discountTax;
taxValue = taxRates[taxRate] - discountTax;
if (_shoppingCartSettings.RoundPrices)
- taxValue = RoundingHelper.RoundPrice(taxValue, _workContext.WorkingCurrency);
+ taxValue = RoundingHelper.RoundPrice(taxValue, _workContextAccessor.WorkContext.WorkingCurrency);
taxRates[taxRate] = taxValue;
}
@@ -424,8 +424,8 @@ public class OrderCalculationService : IOrderCalculationService
if (_shoppingCartSettings.RoundPrices)
{
- discountAmountInclTax = RoundingHelper.RoundPrice(discountAmountInclTax, _workContext.WorkingCurrency);
- discountAmountExclTax = RoundingHelper.RoundPrice(discountAmountExclTax, _workContext.WorkingCurrency);
+ discountAmountInclTax = RoundingHelper.RoundPrice(discountAmountInclTax, _workContextAccessor.WorkContext.WorkingCurrency);
+ discountAmountExclTax = RoundingHelper.RoundPrice(discountAmountExclTax, _workContextAccessor.WorkContext.WorkingCurrency);
}
if (includingTax)
@@ -443,7 +443,7 @@ public class OrderCalculationService : IOrderCalculationService
subTotalWithDiscount = 0;
if (_shoppingCartSettings.RoundPrices)
- subTotalWithDiscount = RoundingHelper.RoundPrice(subTotalWithDiscount, _workContext.WorkingCurrency);
+ subTotalWithDiscount = RoundingHelper.RoundPrice(subTotalWithDiscount, _workContextAccessor.WorkContext.WorkingCurrency);
return (discountAmount, appliedDiscounts, subTotalWithoutDiscount, subTotalWithDiscount, taxRates);
}
@@ -473,7 +473,7 @@ public class OrderCalculationService : IOrderCalculationService
/// <returns>A value indicating whether shipping is free</returns>
public virtual async Task<bool> IsFreeShipping(IList<ShoppingCartItem> cart)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
if (customer != null)
{
//check whether customer has a free shipping
@@ -525,9 +525,9 @@ public class OrderCalculationService : IOrderCalculationService
//discount
var (discountAmount, applyDiscounts) = await GetShippingDiscount(
- _workContext.CurrentCustomer,
- _workContext.CurrentStore,
- _workContext.WorkingCurrency, adjustedRate);
+ _workContextAccessor.WorkContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.CurrentStore,
+ _workContextAccessor.WorkContext.WorkingCurrency, adjustedRate);
appliedDiscounts = applyDiscounts;
adjustedRate -= discountAmount;
@@ -536,7 +536,7 @@ public class OrderCalculationService : IOrderCalculationService
adjustedRate = 0;
if (_shoppingCartSettings.RoundPrices)
- adjustedRate = RoundingHelper.RoundPrice(adjustedRate, _workContext.WorkingCurrency);
+ adjustedRate = RoundingHelper.RoundPrice(adjustedRate, _workContextAccessor.WorkContext.WorkingCurrency);
return (adjustedRate, appliedDiscounts);
}
@@ -550,7 +550,7 @@ public class OrderCalculationService : IOrderCalculationService
Task<(double? shoppingCartShippingTotal, double taxRate, List<ApplyDiscount> appliedDiscounts)>
GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart)
{
- var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
+ var includingTax = _workContextAccessor.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax;
return await GetShoppingCartShippingTotal(cart, includingTax);
}
@@ -569,7 +569,7 @@ public class OrderCalculationService : IOrderCalculationService
var appliedDiscounts = new List<ApplyDiscount>();
double taxRate = 0;
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var currency = await _currencyService.GetPrimaryExchangeRateCurrency();
var isFreeShipping = await IsFreeShipping(cart);
@@ -580,7 +580,7 @@ public class OrderCalculationService : IOrderCalculationService
if (customer != null)
shippingOption =
customer.GetUserFieldFromEntity<ShippingOption>(SystemCustomerFieldNames.SelectedShippingOption,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
if (shippingOption != null)
{
@@ -597,8 +597,8 @@ public class OrderCalculationService : IOrderCalculationService
shippingAddress = customer.ShippingAddress;
var shippingRateMethods =
- await _shippingService.LoadActiveShippingRateCalculationProviders(_workContext.CurrentCustomer,
- _workContext.CurrentStore.Id, cart);
+ await _shippingService.LoadActiveShippingRateCalculationProviders(_workContextAccessor.WorkContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.CurrentStore.Id, cart);
if (!shippingRateMethods.Any() && !_shippingSettings.AllowPickUpInStore)
throw new GrandException("Shipping rate method could not be loaded");
@@ -609,7 +609,7 @@ public class OrderCalculationService : IOrderCalculationService
var shippingOptionRequest = await _shippingService.CreateShippingOptionRequests(customer, cart,
shippingAddress,
- _workContext.CurrentStore);
+ _workContextAccessor.WorkContext.CurrentStore);
double? fixedRate = null;
//calculate fixed rates for each request-package
@@ -670,12 +670,12 @@ public class OrderCalculationService : IOrderCalculationService
var taxRates = new SortedDictionary<double, double>();
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var paymentMethodSystemName = "";
if (customer != null)
paymentMethodSystemName = customer.GetUserFieldFromEntity<string>(
SystemCustomerFieldNames.SelectedPaymentMethod,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
//order sub total (items + checkout attributes)
double subTotalTaxTotal = 0;
@@ -761,7 +761,7 @@ public class OrderCalculationService : IOrderCalculationService
taxTotal = 0;
//round tax
if (_shoppingCartSettings.RoundPrices)
- taxTotal = RoundingHelper.RoundPrice(taxTotal, _workContext.WorkingCurrency);
+ taxTotal = RoundingHelper.RoundPrice(taxTotal, _workContextAccessor.WorkContext.WorkingCurrency);
return (taxTotal, taxRates);
}
@@ -783,9 +783,9 @@ public class OrderCalculationService : IOrderCalculationService
var redeemedLoyaltyPoints = 0;
double redeemedLoyaltyPointsAmount = 0;
- var paymentMethodSystemName = _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(
+ var paymentMethodSystemName = _workContextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<string>(
SystemCustomerFieldNames.SelectedPaymentMethod,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
//subtotal without tax
var subTotal = await GetShoppingCartSubTotal(cart, false);
@@ -803,7 +803,7 @@ public class OrderCalculationService : IOrderCalculationService
await _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);
paymentMethodAdditionalFeeWithoutTax =
(await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false,
- _workContext.CurrentCustomer))
+ _workContextAccessor.WorkContext.CurrentCustomer))
.paymentPrice;
}
@@ -818,12 +818,12 @@ public class OrderCalculationService : IOrderCalculationService
resultTemp += paymentMethodAdditionalFeeWithoutTax;
resultTemp += shoppingCartTax;
if (_shoppingCartSettings.RoundPrices)
- resultTemp = RoundingHelper.RoundPrice(resultTemp, _workContext.WorkingCurrency);
+ resultTemp = RoundingHelper.RoundPrice(resultTemp, _workContextAccessor.WorkContext.WorkingCurrency);
#region Order total discount
- var totalDiscount = await GetOrderTotalDiscount(_workContext.CurrentCustomer, _workContext.CurrentStore,
- _workContext.WorkingCurrency, resultTemp);
+ var totalDiscount = await GetOrderTotalDiscount(_workContextAccessor.WorkContext.CurrentCustomer, _workContextAccessor.WorkContext.CurrentStore,
+ _workContextAccessor.WorkContext.WorkingCurrency, resultTemp);
var discountAmount = totalDiscount.orderTotalDiscount;
var appliedDiscounts = totalDiscount.appliedDiscounts;
@@ -837,7 +837,7 @@ public class OrderCalculationService : IOrderCalculationService
if (resultTemp < 0)
resultTemp = 0;
if (_shoppingCartSettings.RoundPrices)
- resultTemp = RoundingHelper.RoundPrice(resultTemp, _workContext.WorkingCurrency);
+ resultTemp = RoundingHelper.RoundPrice(resultTemp, _workContextAccessor.WorkContext.WorkingCurrency);
#endregion
@@ -846,8 +846,8 @@ public class OrderCalculationService : IOrderCalculationService
var appliedGiftVouchers = new List<AppliedGiftVoucher>();
//we don't apply gift vouchers for recurring products
var giftVouchers =
- await GetActiveGiftVouchers(_workContext.CurrentCustomer, _workContext.WorkingCurrency,
- _workContext.CurrentStore);
+ await GetActiveGiftVouchers(_workContextAccessor.WorkContext.CurrentCustomer, _workContextAccessor.WorkContext.WorkingCurrency,
+ _workContextAccessor.WorkContext.CurrentStore);
if (giftVouchers != null)
foreach (var gc in giftVouchers)
if (resultTemp > 0)
@@ -870,7 +870,7 @@ public class OrderCalculationService : IOrderCalculationService
if (resultTemp < 0)
resultTemp = 0;
if (_shoppingCartSettings.RoundPrices)
- resultTemp = RoundingHelper.RoundPrice(resultTemp, _workContext.WorkingCurrency);
+ resultTemp = RoundingHelper.RoundPrice(resultTemp, _workContextAccessor.WorkContext.WorkingCurrency);
if (!shoppingCartShipping.HasValue)
//we have errors
@@ -883,15 +883,15 @@ public class OrderCalculationService : IOrderCalculationService
if (_loyaltyPointsSettings.Enabled)
{
- useLoyaltyPoints ??= _workContext.CurrentCustomer.GetUserFieldFromEntity<bool>(
+ useLoyaltyPoints ??= _workContextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<bool>(
SystemCustomerFieldNames.UseLoyaltyPointsDuringCheckout,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
if (useLoyaltyPoints.Value)
{
var loyaltyPointsBalance =
- await _loyaltyPointsService.GetLoyaltyPointsBalance(_workContext.CurrentCustomer.Id,
- _workContext.CurrentStore.Id);
+ await _loyaltyPointsService.GetLoyaltyPointsBalance(_workContextAccessor.WorkContext.CurrentCustomer.Id,
+ _workContextAccessor.WorkContext.CurrentStore.Id);
if (CheckMinimumLoyaltyPointsToUseRequirement(loyaltyPointsBalance))
{
var loyaltyPointsBalanceAmount = await ConvertLoyaltyPointsToAmount(loyaltyPointsBalance);
@@ -902,14 +902,14 @@ public class OrderCalculationService : IOrderCalculationService
redeemedLoyaltyPoints = loyaltyPointsBalance;
redeemedLoyaltyPointsAmount =
await _currencyService.ConvertFromPrimaryStoreCurrency(loyaltyPointsBalanceAmount,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
}
else
{
redeemedLoyaltyPointsAmount = orderTotal;
redeemedLoyaltyPoints = ConvertAmountToLoyaltyPoints(
await _currencyService.ConvertToPrimaryStoreCurrency(redeemedLoyaltyPointsAmount,
- _workContext.WorkingCurrency));
+ _workContextAccessor.WorkContext.WorkingCurrency));
}
}
}
@@ -920,7 +920,7 @@ public class OrderCalculationService : IOrderCalculationService
orderTotal -= redeemedLoyaltyPointsAmount;
if (_shoppingCartSettings.RoundPrices)
- orderTotal = RoundingHelper.RoundPrice(orderTotal, _workContext.WorkingCurrency);
+ orderTotal = RoundingHelper.RoundPrice(orderTotal, _workContextAccessor.WorkContext.WorkingCurrency);
return (orderTotal, discountAmount, appliedDiscounts, appliedGiftVouchers, redeemedLoyaltyPoints,
redeemedLoyaltyPointsAmount);
@@ -937,7 +937,7 @@ public class OrderCalculationService : IOrderCalculationService
return 0;
var result = loyaltyPoints * _loyaltyPointsSettings.ExchangeRate;
- if (_shoppingCartSettings.RoundPrices) result = RoundingHelper.RoundPrice(result, _workContext.WorkingCurrency);
+ if (_shoppingCartSettings.RoundPrices) result = RoundingHelper.RoundPrice(result, _workContextAccessor.WorkContext.WorkingCurrency);
return await Task.FromResult(result);
}
diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs
index fa4e632ac..161d01099 100644
--- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs
+++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs
@@ -22,14 +22,14 @@ public class ShoppingCartService : IShoppingCartService
#region Ctor
public ShoppingCartService(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IProductService productService,
ICustomerService customerService,
IMediator mediator,
IShoppingCartValidator shoppingCartValidator,
ShoppingCartSettings shoppingCartSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_productService = productService;
_customerService = customerService;
_mediator = mediator;
@@ -41,7 +41,7 @@ public class ShoppingCartService : IShoppingCartService
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IProductService _productService;
private readonly ICustomerService _customerService;
private readonly IMediator _mediator;
@@ -62,7 +62,7 @@ public class ShoppingCartService : IShoppingCartService
params ShoppingCartType[] shoppingCartType)
{
var model = new List<ShoppingCartItem>();
- var cart = _workContext.CurrentCustomer.ShoppingCartItems.ToList();
+ var cart = _workContextAccessor.WorkContext.CurrentCustomer.ShoppingCartItems.ToList();
if (!string.IsNullOrEmpty(storeId))
cart = cart.LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, storeId).ToList();
@@ -431,9 +431,9 @@ public class ShoppingCartService : IShoppingCartService
}
//move selected checkout attributes
- var checkoutAttributes = fromCustomer.GetUserFieldFromEntity<List<CustomAttribute>>(SystemCustomerFieldNames.CheckoutAttributes, _workContext.CurrentStore.Id);
+ var checkoutAttributes = fromCustomer.GetUserFieldFromEntity<List<CustomAttribute>>(SystemCustomerFieldNames.CheckoutAttributes, _workContextAccessor.WorkContext.CurrentStore.Id);
await _customerService.UpdateUserField(toCustomer, SystemCustomerFieldNames.CheckoutAttributes, checkoutAttributes,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
}
#endregion
diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs
index aba21690f..4391b1f72 100644
--- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs
+++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs
@@ -17,14 +17,14 @@ public class ShoppingCartValidator : IShoppingCartValidator
private readonly IMediator _mediator;
private readonly IValidatorFactory _validatorFactory;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public ShoppingCartValidator(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator,
IValidatorFactory validatorFactory)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_validatorFactory = validatorFactory;
}
@@ -128,8 +128,8 @@ public class ShoppingCartValidator : IShoppingCartValidator
checkoutAttributes ??= new List<CustomAttribute>();
var result = await _validatorFactory.GetValidator<ShoppingCartWarningsValidatorRecord>()
- .ValidateAsync(new ShoppingCartWarningsValidatorRecord(_workContext.CurrentCustomer,
- _workContext.CurrentStore, shoppingCart));
+ .ValidateAsync(new ShoppingCartWarningsValidatorRecord(_workContextAccessor.WorkContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.CurrentStore, shoppingCart));
if (!result.IsValid)
warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));
@@ -138,8 +138,8 @@ public class ShoppingCartValidator : IShoppingCartValidator
{
var resultCheckoutAttributes = await _validatorFactory
.GetValidator<ShoppingCartCheckoutAttributesValidatorRecord>().ValidateAsync(
- new ShoppingCartCheckoutAttributesValidatorRecord(_workContext.CurrentCustomer,
- _workContext.CurrentStore,
+ new ShoppingCartCheckoutAttributesValidatorRecord(_workContextAccessor.WorkContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.CurrentStore,
shoppingCart, checkoutAttributes));
if (!resultCheckoutAttributes.IsValid)
warnings.AddRange(resultCheckoutAttributes.Errors.Select(x => x.ErrorMessage));
@@ -150,8 +150,8 @@ public class ShoppingCartValidator : IShoppingCartValidator
{
var resultCheckoutAttributes = await _validatorFactory
.GetValidator<ShoppingCartTotalAmountValidatorRecord>().ValidateAsync(
- new ShoppingCartTotalAmountValidatorRecord(_workContext.CurrentCustomer,
- _workContext.WorkingCurrency, shoppingCart));
+ new ShoppingCartTotalAmountValidatorRecord(_workContextAccessor.WorkContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.WorkingCurrency, shoppingCart));
if (!resultCheckoutAttributes.IsValid)
warnings.AddRange(resultCheckoutAttributes.Errors.Select(x => x.ErrorMessage));
}
@@ -170,7 +170,7 @@ public class ShoppingCartValidator : IShoppingCartValidator
var warnings = new List<string>();
var result = await _validatorFactory.GetValidator<ShoppingCartCommonWarningsValidatorRecord>().ValidateAsync(
- new ShoppingCartCommonWarningsValidatorRecord(customer, _workContext.CurrentStore, currentCart,
+ new ShoppingCartCommonWarningsValidatorRecord(customer, _workContextAccessor.WorkContext.CurrentStore, currentCart,
product, shoppingCartType, rentalStartDate, rentalEndDate, quantity, reservationId));
if (!result.IsValid)
warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));
@@ -228,8 +228,8 @@ public class ShoppingCartValidator : IShoppingCartValidator
if (!product.RequireOtherProducts) return warnings;
var result = await _validatorFactory.GetValidator<ShoppingCartRequiredProductValidatorRecord>()
- .ValidateAsync(new ShoppingCartRequiredProductValidatorRecord(_workContext.CurrentCustomer,
- _workContext.CurrentStore, product, shoppingCartItem));
+ .ValidateAsync(new ShoppingCartRequiredProductValidatorRecord(_workContextAccessor.WorkContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.CurrentStore, product, shoppingCartItem));
if (!result.IsValid)
warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));
return warnings;
diff --git a/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs b/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs
index 77d5c1ea3..df35f933b 100644
--- a/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs
+++ b/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs
@@ -20,7 +20,7 @@ public class KnowledgebaseService : IKnowledgebaseService
private readonly IRepository<KnowledgebaseArticle> _knowledgebaseArticleRepository;
private readonly IRepository<KnowledgebaseCategory> _knowledgebaseCategoryRepository;
private readonly IMediator _mediator;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
/// <summary>
/// Ctor
@@ -30,14 +30,14 @@ public class KnowledgebaseService : IKnowledgebaseService
IRepository<KnowledgebaseArticle> knowledgebaseArticleRepository,
IRepository<KnowledgebaseArticleComment> articleCommentRepository,
IMediator mediator,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ICacheBase cacheBase, AccessControlConfig accessControlConfig)
{
_knowledgebaseCategoryRepository = knowledgebaseCategoryRepository;
_knowledgebaseArticleRepository = knowledgebaseArticleRepository;
_articleCommentRepository = articleCommentRepository;
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_cacheBase = cacheBase;
_accessControlConfig = accessControlConfig;
}
@@ -92,8 +92,8 @@ public class KnowledgebaseService : IKnowledgebaseService
public virtual async Task<KnowledgebaseCategory> GetPublicKnowledgebaseCategory(string id)
{
var key = string.Format(CacheKey.KNOWLEDGEBASE_CATEGORY_BY_ID, id,
- _workContext.CurrentCustomer.GetCustomerGroupIds(),
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds(),
+ _workContextAccessor.WorkContext.CurrentStore.Id);
return await _cacheBase.GetAsync(key, async () =>
{
var query = from p in _knowledgebaseCategoryRepository.Table
@@ -105,7 +105,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreAcl)
{
//Limited to customer groups rules
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -114,7 +114,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreStoreLimitations)
//Store acl
query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)
+ where !p.LimitedToStores || p.Stores.Contains(_workContextAccessor.WorkContext.CurrentStore.Id)
select p;
var toReturn = await Task.FromResult(query.FirstOrDefault());
@@ -168,7 +168,7 @@ public class KnowledgebaseService : IKnowledgebaseService
select p;
if (!_accessControlConfig.IgnoreAcl)
{
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -240,8 +240,8 @@ public class KnowledgebaseService : IKnowledgebaseService
public virtual async Task<List<KnowledgebaseCategory>> GetPublicKnowledgebaseCategories()
{
var key = string.Format(CacheKey.KNOWLEDGEBASE_CATEGORIES,
- string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),
- _workContext.CurrentStore.Id);
+ string.Join(",", _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()),
+ _workContextAccessor.WorkContext.CurrentStore.Id);
return await _cacheBase.GetAsync(key, async () =>
{
var query = from p in _knowledgebaseCategoryRepository.Table
@@ -251,7 +251,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreAcl)
{
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -260,7 +260,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreStoreLimitations)
//Store acl
query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)
+ where !p.LimitedToStores || p.Stores.Contains(_workContextAccessor.WorkContext.CurrentStore.Id)
select p;
query = query.OrderBy(x => x.DisplayOrder);
return await Task.FromResult(query.ToList());
@@ -273,8 +273,8 @@ public class KnowledgebaseService : IKnowledgebaseService
/// <returns>List of public knowledge base articles</returns>
public virtual async Task<List<KnowledgebaseArticle>> GetPublicKnowledgebaseArticles()
{
- var key = string.Format(CacheKey.ARTICLES, string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),
- _workContext.CurrentStore.Id);
+ var key = string.Format(CacheKey.ARTICLES, string.Join(",", _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()),
+ _workContextAccessor.WorkContext.CurrentStore.Id);
return await _cacheBase.GetAsync(key, async () =>
{
@@ -285,7 +285,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreAcl)
{
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -294,7 +294,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreStoreLimitations)
//Store acl
query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)
+ where !p.LimitedToStores || p.Stores.Contains(_workContextAccessor.WorkContext.CurrentStore.Id)
select p;
query = query.OrderBy(x => x.DisplayOrder);
@@ -309,8 +309,8 @@ public class KnowledgebaseService : IKnowledgebaseService
public virtual async Task<KnowledgebaseArticle> GetPublicKnowledgebaseArticle(string id)
{
var key = string.Format(CacheKey.ARTICLE_BY_ID, id,
- string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),
- _workContext.CurrentStore.Id);
+ string.Join(",", _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()),
+ _workContextAccessor.WorkContext.CurrentStore.Id);
return await _cacheBase.GetAsync(key, async () =>
{
var query = from p in _knowledgebaseArticleRepository.Table
@@ -321,7 +321,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreAcl)
{
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -330,7 +330,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreStoreLimitations)
//Store acl
query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)
+ where !p.LimitedToStores || p.Stores.Contains(_workContextAccessor.WorkContext.CurrentStore.Id)
select p;
return await Task.FromResult(query.FirstOrDefault());
@@ -344,8 +344,8 @@ public class KnowledgebaseService : IKnowledgebaseService
public virtual async Task<List<KnowledgebaseArticle>> GetPublicKnowledgebaseArticlesByCategory(string categoryId)
{
var key = string.Format(CacheKey.ARTICLES_BY_CATEGORY_ID, categoryId,
- string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),
- _workContext.CurrentStore.Id);
+ string.Join(",", _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()),
+ _workContextAccessor.WorkContext.CurrentStore.Id);
return await _cacheBase.GetAsync(key, async () =>
{
var query = from p in _knowledgebaseArticleRepository.Table
@@ -356,7 +356,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreAcl)
{
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -365,7 +365,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreStoreLimitations)
//Store acl
query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)
+ where !p.LimitedToStores || p.Stores.Contains(_workContextAccessor.WorkContext.CurrentStore.Id)
select p;
query = query.OrderBy(x => x.DisplayOrder);
return await Task.FromResult(query.ToList());
@@ -379,8 +379,8 @@ public class KnowledgebaseService : IKnowledgebaseService
public virtual async Task<List<KnowledgebaseArticle>> GetPublicKnowledgebaseArticlesByKeyword(string keyword)
{
var key = string.Format(CacheKey.ARTICLES_BY_KEYWORD, keyword,
- string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),
- _workContext.CurrentStore.Id);
+ string.Join(",", _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()),
+ _workContextAccessor.WorkContext.CurrentStore.Id);
return await _cacheBase.GetAsync(key, async () =>
{
@@ -395,7 +395,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreAcl)
{
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -404,7 +404,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreStoreLimitations)
//Store acl
query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)
+ where !p.LimitedToStores || p.Stores.Contains(_workContextAccessor.WorkContext.CurrentStore.Id)
select p;
query = query.OrderBy(x => x.DisplayOrder);
return await Task.FromResult(query.ToList());
@@ -418,8 +418,8 @@ public class KnowledgebaseService : IKnowledgebaseService
public virtual async Task<List<KnowledgebaseCategory>> GetPublicKnowledgebaseCategoriesByKeyword(string keyword)
{
var key = string.Format(CacheKey.KNOWLEDGEBASE_CATEGORIES_BY_KEYWORD, keyword,
- string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),
- _workContext.CurrentStore.Id);
+ string.Join(",", _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()),
+ _workContextAccessor.WorkContext.CurrentStore.Id);
return await _cacheBase.GetAsync(key, async () =>
{
var query = from p in _knowledgebaseCategoryRepository.Table
@@ -433,7 +433,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreAcl)
{
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -442,7 +442,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreStoreLimitations)
//Store acl
query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)
+ where !p.LimitedToStores || p.Stores.Contains(_workContextAccessor.WorkContext.CurrentStore.Id)
select p;
query = query.OrderBy(x => x.DisplayOrder);
return await Task.FromResult(query.ToList());
@@ -456,8 +456,8 @@ public class KnowledgebaseService : IKnowledgebaseService
public virtual async Task<List<KnowledgebaseArticle>> GetHomepageKnowledgebaseArticles()
{
var key = string.Format(CacheKey.HOMEPAGE_ARTICLES,
- string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),
- _workContext.CurrentStore.Id);
+ string.Join(",", _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()),
+ _workContextAccessor.WorkContext.CurrentStore.Id);
return await _cacheBase.GetAsync(key, async () =>
{
var query = from p in _knowledgebaseArticleRepository.Table
@@ -468,7 +468,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreAcl)
{
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
@@ -477,7 +477,7 @@ public class KnowledgebaseService : IKnowledgebaseService
if (!_accessControlConfig.IgnoreStoreLimitations)
//Store acl
query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(_workContext.CurrentStore.Id)
+ where !p.LimitedToStores || p.Stores.Contains(_workContextAccessor.WorkContext.CurrentStore.Id)
select p;
query = query.OrderBy(x => x.DisplayOrder);
return await Task.FromResult(query.ToList());
diff --git a/src/Business/Grand.Business.Cms/Services/NewsService.cs b/src/Business/Grand.Business.Cms/Services/NewsService.cs
index 08de1ea1c..31145a467 100644
--- a/src/Business/Grand.Business.Cms/Services/NewsService.cs
+++ b/src/Business/Grand.Business.Cms/Services/NewsService.cs
@@ -19,11 +19,11 @@ public class NewsService : INewsService
public NewsService(IRepository<NewsItem> newsItemRepository,
IMediator mediator,
- IWorkContext workContext, AccessControlConfig accessControlConfig)
+ IWorkContextAccessor workContextAccessor, AccessControlConfig accessControlConfig)
{
_newsItemRepository = newsItemRepository;
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_accessControlConfig = accessControlConfig;
}
@@ -33,7 +33,7 @@ public class NewsService : INewsService
private readonly IRepository<NewsItem> _newsItemRepository;
private readonly IMediator _mediator;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly AccessControlConfig _accessControlConfig;
#endregion
@@ -83,7 +83,7 @@ public class NewsService : INewsService
{
if (!ignoreAcl && !_accessControlConfig.IgnoreAcl)
{
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
diff --git a/src/Business/Grand.Business.Cms/Services/PageService.cs b/src/Business/Grand.Business.Cms/Services/PageService.cs
index 36a0faeee..ce98ac7b1 100644
--- a/src/Business/Grand.Business.Cms/Services/PageService.cs
+++ b/src/Business/Grand.Business.Cms/Services/PageService.cs
@@ -20,13 +20,13 @@ public class PageService : IPageService
#region Ctor
public PageService(IRepository<Page> pageRepository,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IAclService aclService,
IMediator mediator,
ICacheBase cacheBase, AccessControlConfig accessControlConfig)
{
_pageRepository = pageRepository;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_aclService = aclService;
_mediator = mediator;
_cacheBase = cacheBase;
@@ -38,7 +38,7 @@ public class PageService : IPageService
#region Fields
private readonly IRepository<Page> _pageRepository;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IAclService _aclService;
private readonly IMediator _mediator;
private readonly ICacheBase _cacheBase;
@@ -105,7 +105,7 @@ public class PageService : IPageService
{
if (!ignoreAcl && !_accessControlConfig.IgnoreAcl)
{
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
diff --git a/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs b/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs
index 3b4363504..d7dd4b0df 100644
--- a/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs
+++ b/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs
@@ -24,11 +24,11 @@ public class TranslationService : ITranslationService
/// <param name="trRepository">Translate resource repository</param>
/// <param name="mediator">Mediator</param>
public TranslationService(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IRepository<TranslationResource> trRepository,
IMediator mediator)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_translationRepository = trRepository;
_mediator = mediator;
}
@@ -40,7 +40,7 @@ public class TranslationService : ITranslationService
private static readonly ConcurrentDictionary<string, IDictionary<string, string>> _cachedResources = new();
private readonly IRepository<TranslationResource> _translationRepository;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
#endregion
@@ -143,7 +143,7 @@ public class TranslationService : ITranslationService
/// <returns>A string representing the requested resource string.</returns>
public virtual string GetResource(string name)
{
- return _workContext.WorkingLanguage != null ? GetResource(name, _workContext.WorkingLanguage.Id) : "";
+ return _workContextAccessor.WorkContext.WorkingLanguage != null ? GetResource(name, _workContextAccessor.WorkContext.WorkingLanguage.Id) : "";
}
/// <summary>
@@ -249,7 +249,7 @@ public class TranslationService : ITranslationService
Name = item.Name.ToLowerInvariant(),
Value = item.Value,
Area = areaEnum,
- CreatedBy = _workContext.CurrentCustomer.Email
+ CreatedBy = _workContextAccessor.WorkContext.CurrentCustomer.Email
});
}
}
diff --git a/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs b/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs
index 2a742962a..6c8479b66 100644
--- a/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs
+++ b/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs
@@ -27,13 +27,13 @@ public class PermissionService : IPermissionService
public PermissionService(
IRepository<Permission> permissionRepository,
IRepository<PermissionAction> permissionActionRepository,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
ICacheBase cacheBase)
{
_permissionRepository = permissionRepository;
_permissionActionRepository = permissionActionRepository;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_cacheBase = cacheBase;
}
@@ -69,7 +69,7 @@ public class PermissionService : IPermissionService
private readonly IRepository<Permission> _permissionRepository;
private readonly IRepository<PermissionAction> _permissionActionRepository;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
private readonly ICacheBase _cacheBase;
@@ -162,7 +162,7 @@ public class PermissionService : IPermissionService
/// <returns>true - authorized; otherwise, false</returns>
public virtual async Task<bool> Authorize(Permission permission)
{
- return await Authorize(permission, _workContext.CurrentCustomer);
+ return await Authorize(permission, _workContextAccessor.WorkContext.CurrentCustomer);
}
/// <summary>
@@ -189,7 +189,7 @@ public class PermissionService : IPermissionService
/// <returns>true - authorized; otherwise, false</returns>
public virtual async Task<bool> Authorize(string permissionSystemName)
{
- return await Authorize(permissionSystemName, _workContext.CurrentCustomer);
+ return await Authorize(permissionSystemName, _workContextAccessor.WorkContext.CurrentCustomer);
}
/// <summary>
@@ -267,7 +267,7 @@ public class PermissionService : IPermissionService
if (!await Authorize(permissionSystemName))
return false;
- var customerGroups = await _groupService.GetAllByIds(_workContext.CurrentCustomer.Groups.ToArray());
+ var customerGroups = await _groupService.GetAllByIds(_workContextAccessor.WorkContext.CurrentCustomer.Groups.ToArray());
foreach (var group in customerGroups)
{
if (!await Authorize(permissionSystemName, group))
diff --git a/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs b/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs
index b92baa29a..051dcaa49 100644
--- a/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs
+++ b/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs
@@ -56,18 +56,6 @@ public class StoreService : IStoreService
});
}
- /// <summary>
- /// Gets all stores
- /// </summary>
- /// <returns>Stores</returns>
- public virtual IList<Store> GetAll()
- {
- return _allStores ??= _cacheBase.Get(CacheKey.STORES_ALL_KEY, () =>
- {
- return _storeRepository.Table.OrderBy(x => x.DisplayOrder).ToList();
- });
- }
-
/// <summary>
/// Gets a store
/// </summary>
diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Common/OrderNotificationCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Common/OrderNotificationCommand.cs
new file mode 100644
index 000000000..c3796fe46
--- /dev/null
+++ b/src/Business/Grand.Business.Core/Commands/Messages/Common/OrderNotificationCommand.cs
@@ -0,0 +1,12 @@
+using Grand.Domain.Customers;
+using Grand.Domain.Orders;
+using Grand.Infrastructure;
+using MediatR;
+
+namespace Grand.Business.Core.Commands.Messages.Common;
+
+public class OrderNotificationCommand : IRequest
+{
+ public Order Order { get; set; }
+ public IWorkContext WorkContext { get; set; }
+}
diff --git a/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs b/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs
index e4fe0e91f..c665cd36f 100644
--- a/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs
+++ b/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs
@@ -67,12 +67,12 @@ public static class TranslateExtensions
/// <returns>Translation value</returns>
public static string GetTranslationEnum<T>(this T enumValue,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
where T : struct
{
- ArgumentNullException.ThrowIfNull(workContext);
+ ArgumentNullException.ThrowIfNull(workContextAccessor);
- return GetTranslationEnum(enumValue, translationService, workContext.WorkingLanguage.Id);
+ return GetTranslationEnum(enumValue, translationService, workContextAccessor.WorkContext.WorkingLanguage.Id);
}
/// <summary>
diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.cs
index f6b100398..446386370 100644
--- a/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.cs
+++ b/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.cs
@@ -13,12 +13,6 @@ public interface IStoreService
/// <returns>Stores</returns>
Task<IList<Store>> GetAllStores();
- /// <summary>
- /// Gets all stores
- /// </summary>
- /// <returns>Stores</returns>
- IList<Store> GetAll();
-
/// <summary>
/// Gets a store
/// </summary>
diff --git a/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs b/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs
index d7aabb6bd..ddaba96b4 100644
--- a/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs
+++ b/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs
@@ -24,7 +24,7 @@ public class CampaignService(
IStoreService storeService,
IMediator mediator,
ILanguageService languageService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
: ICampaignService
{
/// <summary>
@@ -252,10 +252,10 @@ public class CampaignService(
(await storeService.GetAllStores()).FirstOrDefault();
builder.AddStoreTokens(store, language, emailAccount)
- .AddNewsLetterSubscriptionTokens(subscription, store, workContext.CurrentHost);
+ .AddNewsLetterSubscriptionTokens(subscription, store, workContextAccessor.WorkContext.CurrentHost);
if (customer != null)
- builder.AddCustomerTokens(customer, store, workContext.CurrentHost, language)
+ builder.AddCustomerTokens(customer, store, workContextAccessor.WorkContext.CurrentHost, language)
.AddShoppingCartTokens(customer, store, language);
var email = new QueuedEmail();
@@ -309,7 +309,7 @@ public class CampaignService(
builder.AddStoreTokens(store, language, emailAccount);
var customer = customerRepository.Table.FirstOrDefault(x => x.Email == email.ToLowerInvariant());
if (customer != null)
- builder.AddCustomerTokens(customer, store, workContext.CurrentHost, language)
+ builder.AddCustomerTokens(customer, store, workContextAccessor.WorkContext.CurrentHost, language)
.AddShoppingCartTokens(customer, store, language);
var liquidObject = await builder.BuildAsync();
diff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs
index 73e9216af..7e288973a 100644
--- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs
+++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs
@@ -17,15 +17,15 @@ namespace Grand.Business.Marketing.Services.Contacts;
public class ContactAttributeParser : IContactAttributeParser
{
private readonly IContactAttributeService _contactAttributeService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public ContactAttributeParser(
IContactAttributeService contactAttributeService,
- IWorkContext workContext
+ IWorkContextAccessor workContextAccessor
)
{
_contactAttributeService = contactAttributeService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
/// <summary>
@@ -213,7 +213,7 @@ public class ContactAttributeParser : IContactAttributeParser
if (allowHyperlinks)
{
var downloadLink =
- $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";
+ $"{_workContextAccessor.WorkContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";
attributeText =
$"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, language.Id)}</a>";
}
diff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs
index d925f303d..5db25916e 100644
--- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs
+++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs
@@ -24,12 +24,12 @@ public class ContactAttributeService : IContactAttributeService
public ContactAttributeService(ICacheBase cacheBase,
IRepository<ContactAttribute> contactAttributeRepository,
IMediator mediator,
- IWorkContext workContext, AccessControlConfig accessControlConfig)
+ IWorkContextAccessor workContextAccessor, AccessControlConfig accessControlConfig)
{
_cacheBase = cacheBase;
_contactAttributeRepository = contactAttributeRepository;
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_accessControlConfig = accessControlConfig;
}
@@ -40,7 +40,7 @@ public class ContactAttributeService : IContactAttributeService
private readonly IRepository<ContactAttribute> _contactAttributeRepository;
private readonly IMediator _mediator;
private readonly ICacheBase _cacheBase;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly AccessControlConfig _accessControlConfig;
#endregion
@@ -87,7 +87,7 @@ public class ContactAttributeService : IContactAttributeService
(ignoreAcl || _accessControlConfig.IgnoreAcl)) return await Task.FromResult(query.ToList());
if (!ignoreAcl && !_accessControlConfig.IgnoreAcl)
{
- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();
+ var allowedCustomerGroupsIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds();
query = from p in query
where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))
select p;
diff --git a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.cs b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.cs
index b4095bcc0..167cfd7f6 100644
--- a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.cs
+++ b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.cs
@@ -12,21 +12,21 @@ public class CustomerCoordinatesService : ICustomerCoordinatesService
{
private readonly IRepository<Customer> _customerRepository;
private readonly IMediator _mediator;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public CustomerCoordinatesService(
IRepository<Customer> customerRepository,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator)
{
_customerRepository = customerRepository;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
}
public Task<(double longitude, double latitude)> GetGeoCoordinate()
{
- return GetGeoCoordinate(_workContext.CurrentCustomer);
+ return GetGeoCoordinate(_workContextAccessor.WorkContext.CurrentCustomer);
}
public async Task<(double longitude, double latitude)> GetGeoCoordinate(Customer customer)
@@ -41,7 +41,7 @@ public class CustomerCoordinatesService : ICustomerCoordinatesService
public async Task SaveGeoCoordinate(double longitude, double latitude)
{
- await SaveGeoCoordinate(_workContext.CurrentCustomer, longitude, latitude);
+ await SaveGeoCoordinate(_workContextAccessor.WorkContext.CurrentCustomer, longitude, latitude);
}
public async Task SaveGeoCoordinate(Customer customer, double longitude, double latitude)
diff --git a/src/Business/Grand.Business.Messages/Services/MessageProviderService.cs b/src/Business/Grand.Business.Messages/Services/MessageProviderService.cs
index 9e52ebcd0..97604bb68 100644
--- a/src/Business/Grand.Business.Messages/Services/MessageProviderService.cs
+++ b/src/Business/Grand.Business.Messages/Services/MessageProviderService.cs
@@ -29,23 +29,24 @@ public class MessageProviderService : IMessageProviderService
{
#region Ctor
- public MessageProviderService(IMessageTemplateService messageTemplateService,
+ public MessageProviderService(
+ IWorkContextAccessor workContextAccessor,
+ IMessageTemplateService messageTemplateService,
IQueuedEmailService queuedEmailService,
ILanguageService languageService,
IEmailAccountService emailAccountService,
IStoreService storeService,
- IStoreHelper storeHelper,
IGroupService groupService,
IMediator mediator,
EmailAccountSettings emailAccountSettings,
CommonSettings commonSettings)
{
+ _workContextAccessor = workContextAccessor;
_messageTemplateService = messageTemplateService;
_queuedEmailService = queuedEmailService;
_languageService = languageService;
_emailAccountService = emailAccountService;
_storeService = storeService;
- _storeHelper = storeHelper;
_groupService = groupService;
_emailAccountSettings = emailAccountSettings;
_commonSettings = commonSettings;
@@ -55,13 +56,12 @@ public class MessageProviderService : IMessageProviderService
#endregion
#region Fields
-
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMessageTemplateService _messageTemplateService;
private readonly IQueuedEmailService _queuedEmailService;
private readonly ILanguageService _languageService;
private readonly IEmailAccountService _emailAccountService;
private readonly IStoreService _storeService;
- private readonly IStoreHelper _storeHelper;
private readonly IGroupService _groupService;
private readonly IMediator _mediator;
@@ -149,7 +149,7 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddCustomerTokens(customer, store, _storeHelper.DomainHost, language, customerNote);
+ .AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language, customerNote);
var liquidObject = await builder.BuildAsync();
//event notification
@@ -315,9 +315,9 @@ public class MessageProviderService : IMessageProviderService
var liquidBuilder = new LiquidObjectBuilder(_mediator);
liquidBuilder.AddStoreTokens(store, language, emailAccount)
- .AddOrderTokens(order, customer, store, _storeHelper.DomainHost);
+ .AddOrderTokens(order, customer, store, _workContextAccessor.WorkContext.CurrentHost);
if (customer != null)
- liquidBuilder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ liquidBuilder.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
var liquidObject = await liquidBuilder.BuildAsync();
//event notification
@@ -447,10 +447,10 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddOrderTokens(order, customer, store, _storeHelper.DomainHost);
+ .AddOrderTokens(order, customer, store, _workContextAccessor.WorkContext.CurrentHost);
if (customer != null)
- builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
var liquidObject = await builder.BuildAsync();
//event notification
@@ -530,10 +530,10 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddOrderTokens(order, customer, store, _storeHelper.DomainHost, vendor: vendor);
+ .AddOrderTokens(order, customer, store, _workContextAccessor.WorkContext.CurrentHost, vendor: vendor);
if (customer != null)
- builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
var liquidObject = await builder.BuildAsync();
//event notification
@@ -596,11 +596,11 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddShipmentTokens(shipment, order, store, _storeHelper.DomainHost, language)
- .AddOrderTokens(order, customer, store, _storeHelper.DomainHost);
+ .AddShipmentTokens(shipment, order, store, _workContextAccessor.WorkContext.CurrentHost, language)
+ .AddOrderTokens(order, customer, store, _workContextAccessor.WorkContext.CurrentHost);
if (customer != null)
- builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
var liquidObject = await builder.BuildAsync();
//event notification
@@ -640,9 +640,9 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddOrderTokens(order, customer, store, _storeHelper.DomainHost, orderNote);
+ .AddOrderTokens(order, customer, store, _workContextAccessor.WorkContext.CurrentHost, orderNote);
if (customer != null)
- builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
var liquidObject = await builder.BuildAsync();
//event notification
@@ -707,7 +707,7 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddNewsLetterSubscriptionTokens(subscription, store, _storeHelper.DomainHost);
+ .AddNewsLetterSubscriptionTokens(subscription, store, _workContextAccessor.WorkContext.CurrentHost);
var liquidObject = await builder.BuildAsync();
//event notification
@@ -753,8 +753,8 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
.AddEmailAFriendTokens(personalMessage, customerEmail, friendsEmail)
- .AddCustomerTokens(customer, store, _storeHelper.DomainHost, language)
- .AddProductTokens(product, language, store, _storeHelper.DomainHost);
+ .AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language)
+ .AddProductTokens(product, language, store, _workContextAccessor.WorkContext.CurrentHost);
var liquidObject = await builder.BuildAsync();
//event notification
@@ -795,7 +795,7 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddCustomerTokens(customer, store, _storeHelper.DomainHost, language)
+ .AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language)
.AddEmailAFriendTokens(personalMessage, customerEmail, friendsEmail);
var liquidObject = await builder.BuildAsync();
@@ -833,8 +833,8 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddCustomerTokens(customer, store, _storeHelper.DomainHost, language)
- .AddProductTokens(product, language, store, _storeHelper.DomainHost);
+ .AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language)
+ .AddProductTokens(product, language, store, _workContextAccessor.WorkContext.CurrentHost);
var liquidObject = await builder.BuildAsync();
liquidObject.AskQuestion = new LiquidAskQuestion(message, customerEmail, fullName, phone);
@@ -914,9 +914,9 @@ public class MessageProviderService : IMessageProviderService
builder.AddStoreTokens(store, language, emailAccount);
if (customer != null)
- builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
- builder.AddMerchandiseReturnTokens(merchandiseReturn, store, _storeHelper.DomainHost, order, language);
+ builder.AddMerchandiseReturnTokens(merchandiseReturn, store, _workContextAccessor.WorkContext.CurrentHost, order, language);
var liquidObject = await builder.BuildAsync();
@@ -971,9 +971,9 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount);
if (customer != null)
- builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
- builder.AddMerchandiseReturnTokens(merchandiseReturn, store, _storeHelper.DomainHost, order, language);
+ builder.AddMerchandiseReturnTokens(merchandiseReturn, store, _workContextAccessor.WorkContext.CurrentHost, order, language);
var liquidObject = await builder.BuildAsync();
//event notification
await _mediator.MessageTokensAdded(messageTemplate, liquidObject);
@@ -1013,9 +1013,9 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount);
if (customer != null)
- builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
- builder.AddMerchandiseReturnTokens(merchandiseReturn, store, _storeHelper.DomainHost, order, language);
+ builder.AddMerchandiseReturnTokens(merchandiseReturn, store, _workContextAccessor.WorkContext.CurrentHost, order, language);
var liquidObject = await builder.BuildAsync();
//event notification
await _mediator.MessageTokensAdded(messageTemplate, liquidObject);
@@ -1056,9 +1056,9 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount);
if (customer != null)
- builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
- builder.AddMerchandiseReturnTokens(merchandiseReturn, store, _storeHelper.DomainHost, order, language,
+ builder.AddMerchandiseReturnTokens(merchandiseReturn, store, _workContextAccessor.WorkContext.CurrentHost, order, language,
merchandiseReturnNote);
var liquidObject = await builder.BuildAsync();
//event notification
@@ -1099,7 +1099,7 @@ public class MessageProviderService : IMessageProviderService
var emailAccount = await GetEmailAccountOfMessageTemplate(messageTemplate, language.Id);
var builder = new LiquidObjectBuilder(_mediator).AddStoreTokens(store, language, emailAccount)
- .AddCustomerTokens(customer, store, _storeHelper.DomainHost, language)
+ .AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language)
.AddVendorTokens(vendor, language);
var liquidObject = await builder.BuildAsync();
@@ -1212,7 +1212,7 @@ public class MessageProviderService : IMessageProviderService
.AddProductReviewTokens(product, productReview);
if (customer != null)
- builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
var liquidObject = await builder.BuildAsync();
//event notification
@@ -1256,7 +1256,7 @@ public class MessageProviderService : IMessageProviderService
.AddVendorReviewTokens(vendor, vendorReview);
if (customer != null)
- builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
builder.AddVendorTokens(vendor, language);
var liquidObject = await builder.BuildAsync();
@@ -1293,7 +1293,7 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddProductTokens(product, language, store, _storeHelper.DomainHost);
+ .AddProductTokens(product, language, store, _workContextAccessor.WorkContext.CurrentHost);
var liquidObject = await builder.BuildAsync();
//event notification
await _mediator.MessageTokensAdded(messageTemplate, liquidObject);
@@ -1330,7 +1330,7 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddProductTokens(product, language, store, _storeHelper.DomainHost)
+ .AddProductTokens(product, language, store, _workContextAccessor.WorkContext.CurrentHost)
.AddAttributeCombinationTokens(product, combination);
var liquidObject = await builder.BuildAsync();
//event notification
@@ -1365,7 +1365,7 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ .AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
var liquidObject = await builder.BuildAsync();
@@ -1396,11 +1396,11 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddBlogCommentTokens(blogPost, blogComment, store, _storeHelper.DomainHost, language);
+ .AddBlogCommentTokens(blogPost, blogComment, store, _workContextAccessor.WorkContext.CurrentHost, language);
var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = blogComment.CustomerId });
if (customer != null && await _groupService.IsRegistered(customer))
- builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
var liquidObject = await builder.BuildAsync();
//event notification
@@ -1437,11 +1437,11 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddArticleCommentTokens(article, articleComment, store, _storeHelper.DomainHost, language);
+ .AddArticleCommentTokens(article, articleComment, store, _workContextAccessor.WorkContext.CurrentHost, language);
var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = articleComment.CustomerId });
if (customer != null && await _groupService.IsRegistered(customer))
- builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
var liquidObject = await builder.BuildAsync();
//event notification
await _mediator.MessageTokensAdded(messageTemplate, liquidObject);
@@ -1475,10 +1475,10 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddNewsCommentTokens(newsItem, newsComment, store, _storeHelper.DomainHost, language);
+ .AddNewsCommentTokens(newsItem, newsComment, store, _workContextAccessor.WorkContext.CurrentHost, language);
var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = newsComment.CustomerId });
if (customer != null)
- builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
var liquidObject = await builder.BuildAsync();
//event notification
@@ -1516,9 +1516,9 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount);
if (customer != null)
- builder.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
- builder.AddOutOfStockTokens(product, subscription, store, _storeHelper.DomainHost, language);
+ builder.AddOutOfStockTokens(product, subscription, store, _workContextAccessor.WorkContext.CurrentHost, language);
var liquidObject = await builder.BuildAsync();
//event notification
await _mediator.MessageTokensAdded(messageTemplate, liquidObject);
@@ -1575,7 +1575,7 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ .AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
var liquidObject = await builder.BuildAsync();
liquidObject.ContactUs = new LiquidContactUs(senderEmail, senderName, body, attrInfo);
@@ -1654,7 +1654,7 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddStoreTokens(store, language, emailAccount)
- .AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ .AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
var liquidObject = await builder.BuildAsync();
liquidObject.ContactUs = new LiquidContactUs(senderEmail, senderName, body, "");
//event notification
@@ -1708,8 +1708,8 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddAuctionTokens(product, bid)
- .AddCustomerTokens(customer, store, _storeHelper.DomainHost, language)
- .AddProductTokens(product, language, store, _storeHelper.DomainHost)
+ .AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language)
+ .AddProductTokens(product, language, store, _workContextAccessor.WorkContext.CurrentHost)
.AddStoreTokens(store, language, emailAccount);
var liquidObject = await builder.BuildAsync();
@@ -1743,7 +1743,7 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddAuctionTokens(product, bid)
- .AddProductTokens(product, language, store, _storeHelper.DomainHost)
+ .AddProductTokens(product, language, store, _workContextAccessor.WorkContext.CurrentHost)
.AddStoreTokens(store, language, emailAccount);
var liquidObject = await builder.BuildAsync();
@@ -1755,7 +1755,7 @@ public class MessageProviderService : IMessageProviderService
var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = item.Key });
if (string.IsNullOrEmpty(languageId))
languageId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId);
- builder2.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder2.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
var liquidObject2 = await builder2.BuildAsync();
//event notification
@@ -1787,7 +1787,7 @@ public class MessageProviderService : IMessageProviderService
var emailAccount = await GetEmailAccountOfMessageTemplate(messageTemplate, language.Id);
var builder = new LiquidObjectBuilder(_mediator);
- builder.AddProductTokens(product, language, store, _storeHelper.DomainHost)
+ builder.AddProductTokens(product, language, store, _workContextAccessor.WorkContext.CurrentHost)
.AddStoreTokens(store, language, emailAccount);
var liquidObject = await builder.BuildAsync();
@@ -1802,7 +1802,7 @@ public class MessageProviderService : IMessageProviderService
if (string.IsNullOrEmpty(languageId))
languageId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId);
- builder2.AddCustomerTokens(customer, store, _storeHelper.DomainHost, language);
+ builder2.AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language);
var liquidObject2 = await builder2.BuildAsync();
//event notification
await _mediator.MessageTokensAdded(messageTemplate, liquidObject2);
@@ -1843,7 +1843,7 @@ public class MessageProviderService : IMessageProviderService
emailAccount = await GetEmailAccountOfMessageTemplate(messageTemplate, language.Id);
builder.AddAuctionTokens(product, bid)
- .AddCustomerTokens(customer, store, _storeHelper.DomainHost, language)
+ .AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language)
.AddStoreTokens(store, language, emailAccount);
}
else
@@ -1855,7 +1855,7 @@ public class MessageProviderService : IMessageProviderService
return 0;
emailAccount = await GetEmailAccountOfMessageTemplate(messageTemplate, language.Id);
- builder.AddProductTokens(product, language, store, _storeHelper.DomainHost);
+ builder.AddProductTokens(product, language, store, _workContextAccessor.WorkContext.CurrentHost);
}
var liquidObject = await builder.BuildAsync();
@@ -1897,7 +1897,7 @@ public class MessageProviderService : IMessageProviderService
var builder = new LiquidObjectBuilder(_mediator);
builder.AddAuctionTokens(product, bid)
- .AddCustomerTokens(customer, store, _storeHelper.DomainHost, language)
+ .AddCustomerTokens(customer, store, _workContextAccessor.WorkContext.CurrentHost, language)
.AddStoreTokens(store, language, emailAccount);
var liquidObject = await builder.BuildAsync();
diff --git a/src/Core/Grand.Infrastructure/IStoreHelper.cs b/src/Core/Grand.Infrastructure/IStoreHelper.cs
deleted file mode 100644
index adbbb3c1f..000000000
--- a/src/Core/Grand.Infrastructure/IStoreHelper.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using Grand.Domain.Stores;
-
-namespace Grand.Infrastructure;
-
-public interface IStoreHelper
-{
- Store StoreHost { get; }
- DomainHost DomainHost { get; }
-
- Task SetStoreCookie(string storeId);
- Task<Store> SetCurrentStore(string storeId);
-}
\ No newline at end of file
diff --git a/src/Core/Grand.Infrastructure/IWorkContext.cs b/src/Core/Grand.Infrastructure/IWorkContext.cs
index a09db321b..83feb039d 100644
--- a/src/Core/Grand.Infrastructure/IWorkContext.cs
+++ b/src/Core/Grand.Infrastructure/IWorkContext.cs
@@ -27,11 +27,6 @@ public interface IWorkContext
/// </summary>
Vendor CurrentVendor { get; }
- /// <summary>
- /// Gets the current host
- /// </summary>
- DomainHost CurrentHost { get; }
-
/// <summary>
/// Get or set current user working language
/// </summary>
@@ -51,39 +46,19 @@ public interface IWorkContext
/// Gets or sets the current store
/// </summary>
Store CurrentStore { get; }
-}
-
-public interface IWorkContextSetter
-{
- /// <summary>
- /// Set the current customer by Middleware
- /// </summary>
- /// <returns></returns>
- Task<Customer> SetCurrentCustomer();
/// <summary>
- /// Set the current customer
- /// </summary>
- /// <returns></returns>
- Task<Customer> SetCurrentCustomer(Customer customer);
-
- /// <summary>
- /// Set the current vendor (logged-in manager)
- /// </summary>
- Task<Vendor> SetCurrentVendor(Customer customer);
-
- /// <summary>
- /// Set current user working language by Middleware
+ /// Gets the current host
/// </summary>
- Task<Language> SetWorkingLanguage(Customer customer);
+ DomainHost CurrentHost { get; }
- /// <summary>
- /// Set current user working currency by Middleware
- /// </summary>
- Task<Currency> SetWorkingCurrency(Customer customer);
+}
+public interface IWorkContextSetter
+{
/// <summary>
- /// Set current tax display type by Middleware
+ /// Initialize the work context
/// </summary>
- Task<TaxDisplayType> SetTaxDisplayType(Customer customer);
+ /// <returns></returns>
+ Task<IWorkContext> InitializeWorkContext(string storeId = null);
}
\ No newline at end of file
diff --git a/src/Core/Grand.Infrastructure/IWorkContextAccessor.cs b/src/Core/Grand.Infrastructure/IWorkContextAccessor.cs
new file mode 100644
index 000000000..3bfd6af71
--- /dev/null
+++ b/src/Core/Grand.Infrastructure/IWorkContextAccessor.cs
@@ -0,0 +1,6 @@
+namespace Grand.Infrastructure;
+
+public interface IWorkContextAccessor
+{
+ IWorkContext WorkContext { get; set; }
+}
diff --git a/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs b/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs
index aba6d153d..f546cbc5e 100644
--- a/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs
+++ b/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs
@@ -10,6 +10,8 @@ namespace Grand.SharedKernel.Extensions;
/// </summary>
public static class CommonHelper
{
+ public const string StoreCookieName = ".Grand.Store";
+
/// <summary>
/// Ensures the subscriber email or throw.
/// </summary>
diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductAttributeCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductAttributeCommandHandler.cs
index 8a4bd9eba..1fdd9718f 100644
--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductAttributeCommandHandler.cs
+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductAttributeCommandHandler.cs
@@ -12,16 +12,16 @@ public class AddProductAttributeCommandHandler : IRequestHandler<AddProductAttri
{
private readonly IProductAttributeService _productAttributeService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public AddProductAttributeCommandHandler(
IProductAttributeService productAttributeService,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_productAttributeService = productAttributeService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<ProductAttributeDto> Handle(AddProductAttributeCommand request,
diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddSpecificationAttributeCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddSpecificationAttributeCommandHandler.cs
index 2b6a264e0..c765314a7 100644
--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddSpecificationAttributeCommandHandler.cs
+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddSpecificationAttributeCommandHandler.cs
@@ -14,16 +14,16 @@ public class
{
private readonly ISpecificationAttributeService _specificationAttributeService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public AddSpecificationAttributeCommandHandler(
ISpecificationAttributeService specificationAttributeService,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_specificationAttributeService = specificationAttributeService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<SpecificationAttributeDto> Handle(AddSpecificationAttributeCommand request,
diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteBrandCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteBrandCommandHandler.cs
index 8ecba5bd2..93e7c6048 100644
--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteBrandCommandHandler.cs
+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteBrandCommandHandler.cs
@@ -10,16 +10,16 @@ public class DeleteBrandCommandHandler : IRequestHandler<DeleteBrandCommand, boo
{
private readonly IBrandService _brandService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public DeleteBrandCommandHandler(
IBrandService brandService,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_brandService = brandService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<bool> Handle(DeleteBrandCommand request, CancellationToken cancellationToken)
diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteCategoryCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteCategoryCommandHandler.cs
index fed6ab6ab..0f8e7ab71 100644
--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteCategoryCommandHandler.cs
+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteCategoryCommandHandler.cs
@@ -10,16 +10,16 @@ public class DeleteCategoryCommandHandler : IRequestHandler<DeleteCategoryComman
{
private readonly ICategoryService _categoryService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public DeleteCategoryCommandHandler(
ICategoryService categoryService,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_categoryService = categoryService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<bool> Handle(DeleteCategoryCommand request, CancellationToken cancellationToken)
diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteCollectionCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteCollectionCommandHandler.cs
index 0022476df..0e9557c50 100644
--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteCollectionCommandHandler.cs
+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteCollectionCommandHandler.cs
@@ -10,16 +10,16 @@ public class DeleteCollectionCommandHandler : IRequestHandler<DeleteCollectionCo
{
private readonly ICollectionService _collectionService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public DeleteCollectionCommandHandler(
ICollectionService collectionService,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_collectionService = collectionService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<bool> Handle(DeleteCollectionCommand request, CancellationToken cancellationToken)
diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductAttributeCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductAttributeCommandHandler.cs
index 00964f172..01cb14ed7 100644
--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductAttributeCommandHandler.cs
+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductAttributeCommandHandler.cs
@@ -10,16 +10,16 @@ public class DeleteProductAttributeCommandHandler : IRequestHandler<DeleteProduc
{
private readonly IProductAttributeService _productAttributeService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public DeleteProductAttributeCommandHandler(
IProductAttributeService productAttributeService,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_productAttributeService = productAttributeService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<bool> Handle(DeleteProductAttributeCommand request, CancellationToken cancellationToken)
diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductCommandHandler.cs
index 190aece43..60a74301b 100644
--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductCommandHandler.cs
+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductCommandHandler.cs
@@ -10,16 +10,16 @@ public class DeleteProductCommandHandler : IRequestHandler<DeleteProductCommand,
{
private readonly IProductService _productService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public DeleteProductCommandHandler(
IProductService productService,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_productService = productService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<bool> Handle(DeleteProductCommand request, CancellationToken cancellationToken)
diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteSpecificationAttributeCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteSpecificationAttributeCommandHandler.cs
index 8d202aca5..ef75913c5 100644
--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteSpecificationAttributeCommandHandler.cs
+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteSpecificationAttributeCommandHandler.cs
@@ -10,16 +10,16 @@ public class DeleteSpecificationAttributeCommandHandler : IRequestHandler<Delete
{
private readonly ISpecificationAttributeService _specificationAttributeService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public DeleteSpecificationAttributeCommandHandler(
ISpecificationAttributeService specificationAttributeService,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_specificationAttributeService = specificationAttributeService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<bool> Handle(DeleteSpecificationAttributeCommand request, CancellationToken cancellationToken)
diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductAttributeCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductAttributeCommandHandler.cs
index 7f956abdf..818af906b 100644
--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductAttributeCommandHandler.cs
+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductAttributeCommandHandler.cs
@@ -12,16 +12,16 @@ public class UpdateProductAttributeCommandHandler : IRequestHandler<UpdateProduc
{
private readonly IProductAttributeService _productAttributeService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public UpdateProductAttributeCommandHandler(
IProductAttributeService productAttributeService,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_productAttributeService = productAttributeService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<ProductAttributeDto> Handle(UpdateProductAttributeCommand request,
diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductStockCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductStockCommandHandler.cs
index bbb14244f..42e50cd3c 100644
--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductStockCommandHandler.cs
+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductStockCommandHandler.cs
@@ -14,7 +14,7 @@ public class UpdateProductStockCommandHandler : IRequestHandler<UpdateProductSto
private readonly IProductService _productService;
private readonly IStockQuantityService _stockQuantityService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public UpdateProductStockCommandHandler(
IProductService productService,
@@ -22,14 +22,14 @@ public class UpdateProductStockCommandHandler : IRequestHandler<UpdateProductSto
IStockQuantityService stockQuantityService,
ITranslationService translationService,
IOutOfStockSubscriptionService outOfStockSubscriptionService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_productService = productService;
_inventoryManageService = inventoryManageService;
_stockQuantityService = stockQuantityService;
_translationService = translationService;
_outOfStockSubscriptionService = outOfStockSubscriptionService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<bool> Handle(UpdateProductStockCommand request, CancellationToken cancellationToken)
diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateSpecificationAttributeCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateSpecificationAttributeCommandHandler.cs
index 3cf3cd827..14b1c9cf1 100644
--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateSpecificationAttributeCommandHandler.cs
+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateSpecificationAttributeCommandHandler.cs
@@ -14,16 +14,16 @@ public class
{
private readonly ISpecificationAttributeService _specificationAttributeService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public UpdateSpecificationAttributeCommandHandler(
ISpecificationAttributeService specificationAttributeService,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_specificationAttributeService = specificationAttributeService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<SpecificationAttributeDto> Handle(UpdateSpecificationAttributeCommand request,
diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/AddCustomerGroupCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/AddCustomerGroupCommandHandler.cs
index f99c1864e..d3a3c85c5 100644
--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/AddCustomerGroupCommandHandler.cs
+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/AddCustomerGroupCommandHandler.cs
@@ -12,16 +12,16 @@ public class AddCustomerGroupCommandHandler : IRequestHandler<AddCustomerGroupCo
{
private readonly IGroupService _groupService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public AddCustomerGroupCommandHandler(
IGroupService groupService,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_groupService = groupService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<CustomerGroupDto> Handle(AddCustomerGroupCommand request, CancellationToken cancellationToken)
diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerCommandHandler.cs
index 585f10d87..2011f37e7 100644
--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerCommandHandler.cs
+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerCommandHandler.cs
@@ -10,16 +10,16 @@ public class DeleteCustomerCommandHandler : IRequestHandler<DeleteCustomerComman
{
private readonly ICustomerService _customerService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public DeleteCustomerCommandHandler(
ICustomerService customerService,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_customerService = customerService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<bool> Handle(DeleteCustomerCommand request, CancellationToken cancellationToken)
diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerGroupCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerGroupCommandHandler.cs
index e34a3375c..b9a46ad4c 100644
--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerGroupCommandHandler.cs
+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerGroupCommandHandler.cs
@@ -10,16 +10,16 @@ public class DeleteCustomerGroupCommandHandler : IRequestHandler<DeleteCustomerG
{
private readonly IGroupService _groupService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public DeleteCustomerGroupCommandHandler(
IGroupService groupService,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_groupService = groupService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<bool> Handle(DeleteCustomerGroupCommand request, CancellationToken cancellationToken)
diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerGroupCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerGroupCommandHandler.cs
index eab836ce8..97c1122f2 100644
--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerGroupCommandHandler.cs
+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerGroupCommandHandler.cs
@@ -12,16 +12,16 @@ public class UpdateCustomerGroupCommandHandler : IRequestHandler<UpdateCustomerG
{
private readonly IGroupService _groupService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public UpdateCustomerGroupCommandHandler(
IGroupService groupService,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_groupService = groupService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<CustomerGroupDto> Handle(UpdateCustomerGroupCommand request, CancellationToken cancellationToken)
diff --git a/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs b/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs
index d40caecff..795c55d01 100644
--- a/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs
+++ b/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs
@@ -27,19 +27,19 @@ public class TokenWebController : ControllerBase
private readonly ICustomerService _customerService;
private readonly IMediator _mediator;
private readonly IRefreshTokenService _refreshTokenService;
- private readonly IStoreHelper _storeHelper;
+ private readonly IWorkContextAccessor _workContextAccessor;
public TokenWebController(
ICustomerService customerService,
IMediator mediator,
- IStoreHelper storeHelper,
+ IWorkContextAccessor workContextAccessor,
IRefreshTokenService refreshTokenService,
IAntiforgery antiforgery,
FrontendAPIConfig apiConfig)
{
_customerService = customerService;
_mediator = mediator;
- _storeHelper = storeHelper;
+ _workContextAccessor = workContextAccessor;
_refreshTokenService = refreshTokenService;
_antiforgery = antiforgery;
_apiConfig = apiConfig;
@@ -56,7 +56,7 @@ public class TokenWebController : ControllerBase
var customer = new Customer {
CustomerGuid = Guid.NewGuid(),
Active = true,
- StoreId = _storeHelper.StoreHost.Id,
+ StoreId = _workContextAccessor.WorkContext.CurrentStore.Id,
LastActivityDateUtc = DateTime.UtcNow
};
diff --git a/src/Plugins/Authentication.Facebook/Infrastructure/Cache/FacebookAuthenticationEventConsumer.cs b/src/Plugins/Authentication.Facebook/Infrastructure/Cache/FacebookAuthenticationEventConsumer.cs
index a1e94db96..402502255 100644
--- a/src/Plugins/Authentication.Facebook/Infrastructure/Cache/FacebookAuthenticationEventConsumer.cs
+++ b/src/Plugins/Authentication.Facebook/Infrastructure/Cache/FacebookAuthenticationEventConsumer.cs
@@ -19,12 +19,12 @@ public class FacebookAuthenticationEventConsumer : INotificationHandler<Register
public FacebookAuthenticationEventConsumer(
ICustomerService customerService,
IMessageProviderService messageProviderService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
CustomerSettings customerSettings)
{
_customerService = customerService;
_messageProviderService = messageProviderService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_customerSettings = customerSettings;
}
@@ -56,11 +56,11 @@ public class FacebookAuthenticationEventConsumer : INotificationHandler<Register
//notifications for admin
if (_customerSettings.NotifyNewCustomerRegistration)
await _messageProviderService.SendCustomerRegisteredMessage(eventMessage.Customer,
- _workContext.CurrentStore, _workContext.WorkingLanguage.Id);
+ _workContextAccessor.WorkContext.CurrentStore, _workContextAccessor.WorkContext.WorkingLanguage.Id);
//send welcome message
- await _messageProviderService.SendCustomerWelcomeMessage(eventMessage.Customer, _workContext.CurrentStore,
- _workContext.WorkingLanguage.Id);
+ await _messageProviderService.SendCustomerWelcomeMessage(eventMessage.Customer, _workContextAccessor.WorkContext.CurrentStore,
+ _workContextAccessor.WorkContext.WorkingLanguage.Id);
}
#endregion
@@ -69,7 +69,7 @@ public class FacebookAuthenticationEventConsumer : INotificationHandler<Register
private readonly ICustomerService _customerService;
private readonly IMessageProviderService _messageProviderService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly CustomerSettings _customerSettings;
#endregion
diff --git a/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationEventConsumer.cs b/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationEventConsumer.cs
index ec42e316a..867202321 100644
--- a/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationEventConsumer.cs
+++ b/src/Plugins/Authentication.Google/Infrastructure/GoogleAuthenticationEventConsumer.cs
@@ -19,13 +19,13 @@ public class GoogleAuthenticationEventConsumer : INotificationHandler<Registered
public GoogleAuthenticationEventConsumer(
ICustomerService customerService,
IMessageProviderService messageProviderService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
CustomerSettings customerSettings
)
{
_customerService = customerService;
_messageProviderService = messageProviderService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_customerSettings = customerSettings;
}
@@ -57,11 +57,11 @@ public class GoogleAuthenticationEventConsumer : INotificationHandler<Registered
//notifications for admin
if (_customerSettings.NotifyNewCustomerRegistration)
await _messageProviderService.SendCustomerRegisteredMessage(eventMessage.Customer,
- _workContext.CurrentStore, _workContext.WorkingLanguage.Id);
+ _workContextAccessor.WorkContext.CurrentStore, _workContextAccessor.WorkContext.WorkingLanguage.Id);
//send welcome message
- await _messageProviderService.SendCustomerWelcomeMessage(eventMessage.Customer, _workContext.CurrentStore,
- _workContext.WorkingLanguage.Id);
+ await _messageProviderService.SendCustomerWelcomeMessage(eventMessage.Customer, _workContextAccessor.WorkContext.CurrentStore,
+ _workContextAccessor.WorkContext.WorkingLanguage.Id);
}
#endregion
@@ -70,7 +70,7 @@ public class GoogleAuthenticationEventConsumer : INotificationHandler<Registered
private readonly ICustomerService _customerService;
private readonly IMessageProviderService _messageProviderService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly CustomerSettings _customerSettings;
#endregion
diff --git a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasAllProductsController.cs b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasAllProductsController.cs
index 704435502..6a4daef46 100644
--- a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasAllProductsController.cs
+++ b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasAllProductsController.cs
@@ -25,12 +25,12 @@ public class HasAllProductsController : BaseAdminPluginController
private readonly IStoreService _storeService;
private readonly ITranslationService _translationService;
private readonly IVendorService _vendorService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IEnumTranslationService _enumTranslationService;
public HasAllProductsController(IDiscountService discountService,
IPermissionService permissionService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ITranslationService translationService,
IStoreService storeService,
IVendorService vendorService,
@@ -39,7 +39,7 @@ public class HasAllProductsController : BaseAdminPluginController
{
_discountService = discountService;
_permissionService = permissionService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_translationService = translationService;
_storeService = storeService;
_vendorService = vendorService;
@@ -123,7 +123,7 @@ public class HasAllProductsController : BaseAdminPluginController
var model = new RequirementAllProductsModel.AddProductModel {
//a vendor should have access only to his products
- IsLoggedInAsVendor = _workContext.CurrentVendor != null
+ IsLoggedInAsVendor = _workContextAccessor.WorkContext.CurrentVendor != null
};
//stores
@@ -159,7 +159,7 @@ public class HasAllProductsController : BaseAdminPluginController
return Content("Access denied");
//a vendor should have access only to his products
- if (_workContext.CurrentVendor != null) model.SearchVendorId = _workContext.CurrentVendor.Id;
+ if (_workContextAccessor.WorkContext.CurrentVendor != null) model.SearchVendorId = _workContextAccessor.WorkContext.CurrentVendor.Id;
var searchCategoryIds = new List<string>();
if (!string.IsNullOrEmpty(model.SearchCategoryId))
searchCategoryIds.Add(model.SearchCategoryId);
diff --git a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasOneProductController.cs b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasOneProductController.cs
index 02bdf423d..ea62e179e 100644
--- a/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasOneProductController.cs
+++ b/src/Plugins/DiscountRules.Standard/Areas/Admin/Controllers/HasOneProductController.cs
@@ -26,12 +26,12 @@ public class HasOneProductController : BaseAdminPluginController
private readonly IStoreService _storeService;
private readonly ITranslationService _translationService;
private readonly IVendorService _vendorService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IEnumTranslationService _enumTranslationService;
public HasOneProductController(IDiscountService discountService,
IPermissionService permissionService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ITranslationService translationService,
IStoreService storeService,
IVendorService vendorService,
@@ -40,7 +40,7 @@ public class HasOneProductController : BaseAdminPluginController
{
_discountService = discountService;
_permissionService = permissionService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_translationService = translationService;
_storeService = storeService;
_vendorService = vendorService;
@@ -122,7 +122,7 @@ public class HasOneProductController : BaseAdminPluginController
var model = new RequirementOneProductModel.AddProductModel {
//a vendor should have access only to his products
- IsLoggedInAsVendor = _workContext.CurrentVendor != null
+ IsLoggedInAsVendor = _workContextAccessor.WorkContext.CurrentVendor != null
};
//stores
@@ -158,7 +158,7 @@ public class HasOneProductController : BaseAdminPluginController
return Content("Access denied");
//a vendor should have access only to his products
- if (_workContext.CurrentVendor != null) model.SearchVendorId = _workContext.CurrentVendor.Id;
+ if (_workContextAccessor.WorkContext.CurrentVendor != null) model.SearchVendorId = _workContextAccessor.WorkContext.CurrentVendor.Id;
var searchCategoryIds = new List<string>();
if (!string.IsNullOrEmpty(model.SearchCategoryId))
diff --git a/src/Plugins/DiscountRules.Standard/Providers/ShoppingCartDiscountRule.cs b/src/Plugins/DiscountRules.Standard/Providers/ShoppingCartDiscountRule.cs
index 1a4cf53be..8b0ad6ebe 100644
--- a/src/Plugins/DiscountRules.Standard/Providers/ShoppingCartDiscountRule.cs
+++ b/src/Plugins/DiscountRules.Standard/Providers/ShoppingCartDiscountRule.cs
@@ -14,15 +14,15 @@ public class ShoppingCartDiscountRule : IDiscountRule
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IProductService _productService;
private readonly ShoppingCartSettings _shoppingCartSettings;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public ShoppingCartDiscountRule(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IProductService productService,
IHttpContextAccessor httpContextAccessor,
ShoppingCartSettings shoppingCartSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_productService = productService;
_httpContextAccessor = httpContextAccessor;
_shoppingCartSettings = shoppingCartSettings;
@@ -50,7 +50,7 @@ public class ShoppingCartDiscountRule : IDiscountRule
return result;
}
- var cart = _workContext.CurrentCustomer.ShoppingCartItems
+ var cart = _workContextAccessor.WorkContext.CurrentCustomer.ShoppingCartItems
.Where(sci => sci.ShoppingCartTypeId == ShoppingCartType.ShoppingCart)
.LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, request.Store.Id)
.ToList();
diff --git a/src/Plugins/Payments.BrainTree/BrainTreePaymentProvider.cs b/src/Plugins/Payments.BrainTree/BrainTreePaymentProvider.cs
index 8408bd7e6..a75e38018 100644
--- a/src/Plugins/Payments.BrainTree/BrainTreePaymentProvider.cs
+++ b/src/Plugins/Payments.BrainTree/BrainTreePaymentProvider.cs
@@ -241,7 +241,7 @@ public class BrainTreePaymentProvider : IPaymentProvider
if (!(result > 0)) return await Task.FromResult(result);
var currencyService = _httpContextAccessor.HttpContext!.RequestServices.GetRequiredService<ICurrencyService>();
- var workContext = _httpContextAccessor.HttpContext!.RequestServices.GetRequiredService<IWorkContext>();
+ var workContext = _httpContextAccessor.HttpContext!.RequestServices.GetRequiredService<IWorkContextAccessor>().WorkContext;
result = await currencyService.ConvertFromPrimaryStoreCurrency(result, workContext.WorkingCurrency);
//return result;
diff --git a/src/Plugins/Payments.BrainTree/Controllers/PaymentBrainTreeController.cs b/src/Plugins/Payments.BrainTree/Controllers/PaymentBrainTreeController.cs
index b11b2291e..75b1dd2c4 100644
--- a/src/Plugins/Payments.BrainTree/Controllers/PaymentBrainTreeController.cs
+++ b/src/Plugins/Payments.BrainTree/Controllers/PaymentBrainTreeController.cs
@@ -19,18 +19,18 @@ public class PaymentBrainTreeController : BasePaymentController
private readonly IOrderCalculationService _orderTotalCalculationService;
private readonly IShoppingCartService _shoppingCartService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public PaymentBrainTreeController(BrainTreePaymentSettings brainTreePaymentSettings,
IOrderCalculationService orderTotalCalculationService,
IShoppingCartService shoppingCartService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ITranslationService translationService)
{
_brainTreePaymentSettings = brainTreePaymentSettings;
_orderTotalCalculationService = orderTotalCalculationService;
_shoppingCartService = shoppingCartService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_translationService = translationService;
}
@@ -40,7 +40,7 @@ public class PaymentBrainTreeController : BasePaymentController
if (_brainTreePaymentSettings.Use3DS)
{
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.ShoppingCart);
if (!cart.Any())
diff --git a/src/Plugins/Payments.BrainTree/Views/PaymentBrainTree/PaymentInfo_3DS.cshtml b/src/Plugins/Payments.BrainTree/Views/PaymentBrainTree/PaymentInfo_3DS.cshtml
index e61289384..c720f4cf4 100644
--- a/src/Plugins/Payments.BrainTree/Views/PaymentBrainTree/PaymentInfo_3DS.cshtml
+++ b/src/Plugins/Payments.BrainTree/Views/PaymentBrainTree/PaymentInfo_3DS.cshtml
@@ -3,7 +3,7 @@
@{
Layout = "";
}
-@inject IWorkContext _workContext
+@inject IWorkContextAccessor _workContextAccessor
<style type="text/css">
.braintree-input {
@@ -115,15 +115,15 @@
amount: '@ViewBag.OrderTotal',
nonce: payload.nonce,
challengeRequested: true,
- email: '@_workContext.CurrentCustomer.BillingAddress?.Email',
+ email: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.Email',
billingAddress: {
- givenName: '@_workContext.CurrentCustomer.BillingAddress?.FirstName',
- surname: '@_workContext.CurrentCustomer.BillingAddress?.LastName',
- phoneNumber: '@_workContext.CurrentCustomer.BillingAddress?.PhoneNumber',
- streetAddress: '@_workContext.CurrentCustomer.BillingAddress?.Address1',
- extendedAddress: '@_workContext.CurrentCustomer.BillingAddress?.Address2',
- locality: '@_workContext.CurrentCustomer.BillingAddress?.City',
- postalCode: '@_workContext.CurrentCustomer.BillingAddress?.ZipPostalCode',
+ givenName: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.FirstName',
+ surname: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.LastName',
+ phoneNumber: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.PhoneNumber',
+ streetAddress: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.Address1',
+ extendedAddress: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.Address2',
+ locality: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.City',
+ postalCode: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.ZipPostalCode',
},
onLookupComplete: function (data, next) {
// use `data` here, then call `next()`
diff --git a/src/Plugins/Payments.CashOnDelivery/Areas/Admin/Controllers/PaymentCashOnDeliveryController.cs b/src/Plugins/Payments.CashOnDelivery/Areas/Admin/Controllers/PaymentCashOnDeliveryController.cs
index 8c7bbf8e6..2d529d9fd 100644
--- a/src/Plugins/Payments.CashOnDelivery/Areas/Admin/Controllers/PaymentCashOnDeliveryController.cs
+++ b/src/Plugins/Payments.CashOnDelivery/Areas/Admin/Controllers/PaymentCashOnDeliveryController.cs
@@ -21,15 +21,15 @@ public class PaymentCashOnDeliveryController : BasePaymentController
private readonly ISettingService _settingService;
private readonly IStoreService _storeService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public PaymentCashOnDeliveryController(IWorkContext workContext,
+ public PaymentCashOnDeliveryController(IWorkContextAccessor workContextAccessor,
IStoreService storeService,
ISettingService settingService,
ITranslationService translationService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_storeService = storeService;
_settingService = settingService;
_translationService = translationService;
@@ -53,7 +53,7 @@ public class PaymentCashOnDeliveryController : BasePaymentController
public async Task<IActionResult> Configure()
{
//load settings for a chosen store scope
- var storeScope = await GetActiveStore(_storeService, _workContext);
+ var storeScope = await GetActiveStore(_storeService, _workContextAccessor.WorkContext);
var cashOnDeliveryPaymentSettings = _settingService.LoadSetting<CashOnDeliveryPaymentSettings>(storeScope);
var model = new ConfigurationModel {
@@ -78,7 +78,7 @@ public class PaymentCashOnDeliveryController : BasePaymentController
return await Configure();
//load settings for a chosen store scope
- var storeScope = await GetActiveStore(_storeService, _workContext);
+ var storeScope = await GetActiveStore(_storeService, _workContextAccessor.WorkContext);
var cashOnDeliveryPaymentSettings = _settingService.LoadSetting<CashOnDeliveryPaymentSettings>(storeScope);
//save settings
diff --git a/src/Plugins/Payments.CashOnDelivery/CashOnDeliveryPaymentProvider.cs b/src/Plugins/Payments.CashOnDelivery/CashOnDeliveryPaymentProvider.cs
index e1f654cc2..fb935724b 100644
--- a/src/Plugins/Payments.CashOnDelivery/CashOnDeliveryPaymentProvider.cs
+++ b/src/Plugins/Payments.CashOnDelivery/CashOnDeliveryPaymentProvider.cs
@@ -103,7 +103,7 @@ public class CashOnDeliveryPaymentProvider : IPaymentProvider
if (!(result > 0)) return result;
var currencyService = _httpContextAccessor.HttpContext!.RequestServices.GetRequiredService<ICurrencyService>();
- var workContext = _httpContextAccessor.HttpContext!.RequestServices.GetRequiredService<IWorkContext>();
+ var workContext = _httpContextAccessor.HttpContext!.RequestServices.GetRequiredService<IWorkContextAccessor>().WorkContext;
result = await currencyService.ConvertFromPrimaryStoreCurrency(result, workContext.WorkingCurrency);
//return result;
diff --git a/src/Plugins/Payments.CashOnDelivery/Controllers/PaymentCashOnDeliveryController.cs b/src/Plugins/Payments.CashOnDelivery/Controllers/PaymentCashOnDeliveryController.cs
index 2e43d9954..486fdf8f3 100644
--- a/src/Plugins/Payments.CashOnDelivery/Controllers/PaymentCashOnDeliveryController.cs
+++ b/src/Plugins/Payments.CashOnDelivery/Controllers/PaymentCashOnDeliveryController.cs
@@ -9,20 +9,20 @@ namespace Payments.CashOnDelivery.Controllers;
public class PaymentCashOnDeliveryController : BasePaymentController
{
private readonly ISettingService _settingService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public PaymentCashOnDeliveryController(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ISettingService settingService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_settingService = settingService;
}
public IActionResult PaymentInfo()
{
var cashOnDeliveryPaymentSettings =
- _settingService.LoadSetting<CashOnDeliveryPaymentSettings>(_workContext.CurrentStore.Id);
+ _settingService.LoadSetting<CashOnDeliveryPaymentSettings>(_workContextAccessor.WorkContext.CurrentStore.Id);
var model = new PaymentInfoModel {
DescriptionText = cashOnDeliveryPaymentSettings.DescriptionText
diff --git a/src/Plugins/Payments.StripeCheckout/Areas/Admin/Controllers/StripeCheckoutController.cs b/src/Plugins/Payments.StripeCheckout/Areas/Admin/Controllers/StripeCheckoutController.cs
index 7c8a3ba8d..ae8ed2ad1 100644
--- a/src/Plugins/Payments.StripeCheckout/Areas/Admin/Controllers/StripeCheckoutController.cs
+++ b/src/Plugins/Payments.StripeCheckout/Areas/Admin/Controllers/StripeCheckoutController.cs
@@ -23,15 +23,15 @@ public class StripeCheckoutController : BasePaymentController
private readonly ISettingService _settingService;
private readonly IStoreService _storeService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public StripeCheckoutController(IWorkContext workContext,
+ public StripeCheckoutController(IWorkContextAccessor workContextAccessor,
IStoreService storeService,
ISettingService settingService,
ITranslationService translationService,
IPermissionService permissionService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_storeService = storeService;
_settingService = settingService;
_translationService = translationService;
@@ -45,7 +45,7 @@ public class StripeCheckoutController : BasePaymentController
return stores.FirstOrDefault()?.Id;
var storeId =
- _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames
+ _workContextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames
.AdminAreaStoreScopeConfiguration);
var store = await _storeService.GetStoreById(storeId);
diff --git a/src/Plugins/Payments.StripeCheckout/Areas/Admin/Views/StripeCheckout/Configure.cshtml b/src/Plugins/Payments.StripeCheckout/Areas/Admin/Views/StripeCheckout/Configure.cshtml
index 70a527373..b72e79a10 100644
--- a/src/Plugins/Payments.StripeCheckout/Areas/Admin/Views/StripeCheckout/Configure.cshtml
+++ b/src/Plugins/Payments.StripeCheckout/Areas/Admin/Views/StripeCheckout/Configure.cshtml
@@ -1,10 +1,10 @@
@inject IUrlHelperFactory UrlHelperFactory
@inject IActionContextAccessor ActionContextAccessor
-@inject IWorkContext WorkContext
+@inject IWorkContextAccessor WorkContextAccessor
@{
Layout = "_ConfigurePlugin";
var urlHelper = UrlHelperFactory.GetUrlHelper(ActionContextAccessor.ActionContext!);
- var webhookUrl = WorkContext.CurrentHost.Url.TrimEnd('/') + urlHelper.RouteUrl(StripeCheckoutDefaults.WebHook);
+ var webhookUrl = WorkContextAccessor.WorkContext.CurrentHost.Url.TrimEnd('/') + urlHelper.RouteUrl(StripeCheckoutDefaults.WebHook);
}
@using Grand.Infrastructure
@using Microsoft.AspNetCore.Mvc.Infrastructure
diff --git a/src/Plugins/Payments.StripeCheckout/Controllers/PaymentStripeCheckoutController.cs b/src/Plugins/Payments.StripeCheckout/Controllers/PaymentStripeCheckoutController.cs
index a8159047d..a4c438c96 100644
--- a/src/Plugins/Payments.StripeCheckout/Controllers/PaymentStripeCheckoutController.cs
+++ b/src/Plugins/Payments.StripeCheckout/Controllers/PaymentStripeCheckoutController.cs
@@ -19,17 +19,17 @@ public class PaymentStripeCheckoutController : BasePaymentController
private readonly IPaymentTransactionService _paymentTransactionService;
private readonly StripeCheckoutPaymentSettings _stripeCheckoutPaymentSettings;
private readonly IStripeCheckoutService _stripeCheckoutService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public PaymentStripeCheckoutController(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IOrderService orderService,
ILogger<PaymentStripeCheckoutController> logger,
IPaymentTransactionService paymentTransactionService,
PaymentSettings paymentSettings,
StripeCheckoutPaymentSettings stripeCheckoutPaymentSettings, IStripeCheckoutService stripeCheckoutService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_orderService = orderService;
_logger = logger;
_paymentTransactionService = paymentTransactionService;
@@ -56,7 +56,7 @@ public class PaymentStripeCheckoutController : BasePaymentController
public async Task<IActionResult> CancelOrder(string orderId)
{
var order = await _orderService.GetOrderById(orderId);
- if (order != null && order.CustomerId == _workContext.CurrentCustomer.Id)
+ if (order != null && order.CustomerId == _workContextAccessor.WorkContext.CurrentCustomer.Id)
return RedirectToRoute("OrderDetails", new { orderId = order.Id });
return RedirectToRoute("HomePage");
diff --git a/src/Plugins/Payments.StripeCheckout/Services/StripeCheckoutService.cs b/src/Plugins/Payments.StripeCheckout/Services/StripeCheckoutService.cs
index 0170aef1b..7509d7800 100644
--- a/src/Plugins/Payments.StripeCheckout/Services/StripeCheckoutService.cs
+++ b/src/Plugins/Payments.StripeCheckout/Services/StripeCheckoutService.cs
@@ -15,16 +15,16 @@ public class StripeCheckoutService : IStripeCheckoutService
private readonly IMediator _mediator;
private readonly IPaymentTransactionService _paymentTransactionService;
private readonly StripeCheckoutPaymentSettings _stripeCheckoutPaymentSettings;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public StripeCheckoutService(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
StripeCheckoutPaymentSettings stripeCheckoutPaymentSettings,
ILogger<StripeCheckoutService> logger,
IMediator mediator,
IPaymentTransactionService paymentTransactionService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_stripeCheckoutPaymentSettings = stripeCheckoutPaymentSettings;
_logger = logger;
_mediator = mediator;
@@ -95,7 +95,7 @@ public class StripeCheckoutService : IStripeCheckoutService
{
StripeConfiguration.ApiKey = _stripeCheckoutPaymentSettings.ApiKey;
- var storeLocation = _workContext.CurrentHost.Url.TrimEnd('/');
+ var storeLocation = _workContextAccessor.WorkContext.CurrentHost.Url.TrimEnd('/');
var options = new SessionCreateOptions {
LineItems = [
diff --git a/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.cs b/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.cs
index 7aedea312..c4186992c 100644
--- a/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.cs
+++ b/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.cs
@@ -25,7 +25,7 @@ public class ByWeightShippingCalcPlugin : IShippingRateCalculationProvider
public ByWeightShippingCalcPlugin(
IShippingMethodService shippingMethodService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ITranslationService translationService,
IProductService productService,
ICheckoutAttributeParser checkoutAttributeParser,
@@ -34,7 +34,7 @@ public class ByWeightShippingCalcPlugin : IShippingRateCalculationProvider
ByWeightShippingSettings byWeightShippingSettings)
{
_shippingMethodService = shippingMethodService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_translationService = translationService;
_productService = productService;
_checkoutAttributeParser = checkoutAttributeParser;
@@ -89,7 +89,7 @@ public class ByWeightShippingCalcPlugin : IShippingRateCalculationProvider
#region Fields
private readonly IShippingMethodService _shippingMethodService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ITranslationService _translationService;
private readonly IProductService _productService;
private readonly ICheckoutAttributeParser _checkoutAttributeParser;
@@ -207,7 +207,7 @@ public class ByWeightShippingCalcPlugin : IShippingRateCalculationProvider
var storeId = getShippingOptionRequest.StoreId;
if (string.IsNullOrEmpty(storeId))
- storeId = _workContext.CurrentStore.Id;
+ storeId = _workContextAccessor.WorkContext.CurrentStore.Id;
var countryId = getShippingOptionRequest.ShippingAddress.CountryId;
var stateProvinceId = getShippingOptionRequest.ShippingAddress.StateProvinceId;
@@ -231,7 +231,7 @@ public class ByWeightShippingCalcPlugin : IShippingRateCalculationProvider
var weight = await GetTotalWeight(getShippingOptionRequest);
var shippingMethods =
- await _shippingMethodService.GetAllShippingMethods(countryId, _workContext.CurrentCustomer);
+ await _shippingMethodService.GetAllShippingMethods(countryId, _workContextAccessor.WorkContext.CurrentCustomer);
foreach (var shippingMethod in shippingMethods)
{
double? rate = null;
@@ -251,10 +251,10 @@ public class ByWeightShippingCalcPlugin : IShippingRateCalculationProvider
if (rate is not null)
{
var shippingOption = new ShippingOption {
- Name = shippingMethod.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- Description = shippingMethod.GetTranslation(x => x.Description, _workContext.WorkingLanguage.Id),
+ Name = shippingMethod.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Description = shippingMethod.GetTranslation(x => x.Description, _workContextAccessor.WorkContext.WorkingLanguage.Id),
Rate = await _currencyService.ConvertFromPrimaryStoreCurrency(rate.Value,
- _workContext.WorkingCurrency)
+ _workContextAccessor.WorkContext.WorkingCurrency)
};
response.ShippingOptions.Add(shippingOption);
}
diff --git a/src/Plugins/Shipping.FixedRateShipping/FixedRateShippingProvider.cs b/src/Plugins/Shipping.FixedRateShipping/FixedRateShippingProvider.cs
index 7629720cb..bf3f9dad4 100644
--- a/src/Plugins/Shipping.FixedRateShipping/FixedRateShippingProvider.cs
+++ b/src/Plugins/Shipping.FixedRateShipping/FixedRateShippingProvider.cs
@@ -20,12 +20,12 @@ public class FixedRateShippingProvider : IShippingRateCalculationProvider
private readonly IShippingMethodService _shippingMethodService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public FixedRateShippingProvider(
IShippingMethodService shippingMethodService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ISettingService settingService,
ICurrencyService currencyService,
ITranslationService translationService,
@@ -33,7 +33,7 @@ public class FixedRateShippingProvider : IShippingRateCalculationProvider
)
{
_shippingMethodService = shippingMethodService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_settingService = settingService;
_currencyService = currencyService;
_translationService = translationService;
@@ -68,10 +68,10 @@ public class FixedRateShippingProvider : IShippingRateCalculationProvider
foreach (var shippingMethod in shippingMethods)
{
var shippingOption = new ShippingOption {
- Name = shippingMethod.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- Description = shippingMethod.GetTranslation(x => x.Description, _workContext.WorkingLanguage.Id),
+ Name = shippingMethod.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Description = shippingMethod.GetTranslation(x => x.Description, _workContextAccessor.WorkContext.WorkingLanguage.Id),
Rate = await _currencyService.ConvertFromPrimaryStoreCurrency(GetRate(shippingMethod.Id),
- _workContext.WorkingCurrency)
+ _workContextAccessor.WorkContext.WorkingCurrency)
};
response.ShippingOptions.Add(shippingOption);
}
diff --git a/src/Plugins/Shipping.ShippingPoint/Controllers/SelectedShippingPointController.cs b/src/Plugins/Shipping.ShippingPoint/Controllers/SelectedShippingPointController.cs
index a4d6138fe..a144e2ce5 100644
--- a/src/Plugins/Shipping.ShippingPoint/Controllers/SelectedShippingPointController.cs
+++ b/src/Plugins/Shipping.ShippingPoint/Controllers/SelectedShippingPointController.cs
@@ -16,20 +16,20 @@ public class SelectedShippingPointController : Controller
private readonly IPriceFormatter _priceFormatter;
private readonly IShippingPointService _shippingPointService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public SelectedShippingPointController(
IShippingPointService shippingPointService,
ICountryService countryService,
IPriceFormatter priceFormatter,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ICurrencyService currencyService,
ITranslationService translationService)
{
_shippingPointService = shippingPointService;
_countryService = countryService;
_priceFormatter = priceFormatter;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_currencyService = currencyService;
_translationService = translationService;
}
@@ -40,8 +40,8 @@ public class SelectedShippingPointController : Controller
if (shippingPoint == null) return Content("ShippingPointController: given Shipping Option doesn't exist");
var rateBase =
await _currencyService.ConvertFromPrimaryStoreCurrency(shippingPoint.PickupFee,
- _workContext.WorkingCurrency);
- var fee = _priceFormatter.FormatPrice(rateBase, _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
+ var fee = _priceFormatter.FormatPrice(rateBase, _workContextAccessor.WorkContext.WorkingCurrency);
var viewModel = new PointModel {
ShippingPointName = shippingPoint.ShippingPointName,
@@ -62,7 +62,7 @@ public class SelectedShippingPointController : Controller
if (parameter != _translationService.GetResource("Shipping.ShippingPoint.PluginName"))
return Content("ShippingPointController: given Shipping Option doesn't exist");
- var shippingPoints = await _shippingPointService.GetAllStoreShippingPoint(_workContext.CurrentStore.Id);
+ var shippingPoints = await _shippingPointService.GetAllStoreShippingPoint(_workContextAccessor.WorkContext.CurrentStore.Id);
var shippingPointsModel = new List<SelectListItem> {
new() { Value = "", Text = _translationService.GetResource("Shipping.ShippingPoint.SelectShippingOption") }
diff --git a/src/Plugins/Shipping.ShippingPoint/ShippingPointRateProvider.cs b/src/Plugins/Shipping.ShippingPoint/ShippingPointRateProvider.cs
index 47193db39..dc8f0efd7 100644
--- a/src/Plugins/Shipping.ShippingPoint/ShippingPointRateProvider.cs
+++ b/src/Plugins/Shipping.ShippingPoint/ShippingPointRateProvider.cs
@@ -23,7 +23,7 @@ public class ShippingPointRateProvider : IShippingRateCalculationProvider
public ShippingPointRateProvider(
IShippingPointService shippingPointService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ICustomerService customerService,
ICountryService countryService,
ICurrencyService currencyService,
@@ -32,7 +32,7 @@ public class ShippingPointRateProvider : IShippingRateCalculationProvider
{
_shippingPointService = shippingPointService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_customerService = customerService;
_countryService = countryService;
_currencyService = currencyService;
@@ -45,7 +45,7 @@ public class ShippingPointRateProvider : IShippingRateCalculationProvider
private readonly IShippingPointService _shippingPointService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ICustomerService _customerService;
private readonly ICountryService _countryService;
private readonly ICurrencyService _currencyService;
@@ -110,25 +110,25 @@ public class ShippingPointRateProvider : IShippingRateCalculationProvider
return new List<string> { _translationService.GetResource("Shipping.ShippingPoint.SelectBeforeProceed") };
//override price
- var offeredShippingOptions = _workContext.CurrentCustomer.GetUserFieldFromEntity<List<ShippingOption>>(SystemCustomerFieldNames.OfferedShippingOptions, _workContext.CurrentStore.Id);
+ var offeredShippingOptions = _workContextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<List<ShippingOption>>(SystemCustomerFieldNames.OfferedShippingOptions, _workContextAccessor.WorkContext.CurrentStore.Id);
offeredShippingOptions.Find(x => x.Name == shippingMethodName).Rate =
await _currencyService.ConvertFromPrimaryStoreCurrency(chosenShippingOption.PickupFee,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
await _customerService.UpdateUserField(
- _workContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.OfferedShippingOptions,
offeredShippingOptions,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
var forCustomer =
$"<strong>{_translationService.GetResource("Shipping.ShippingPoint.Fields.ShippingPointName")}:</strong> {chosenShippingOption.ShippingPointName}<br><strong>{_translationService.GetResource("Shipping.ShippingPoint.Fields.Description")}:</strong> {chosenShippingOption.Description}<br>";
await _customerService.UpdateUserField(
- _workContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.ShippingOptionAttributeDescription,
forCustomer,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
var serializedObject = new ShippingPointSerializable {
Id = chosenShippingOption.Id,
@@ -152,10 +152,10 @@ public class ShippingPointRateProvider : IShippingRateCalculationProvider
serializedAttribute = stringBuilder.ToString();
}
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.ShippingOptionAttribute,
serializedAttribute,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
return new List<string>();
}
diff --git a/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.cs b/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.cs
index a54b4b5e5..34a5eee53 100644
--- a/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.cs
+++ b/src/Plugins/Tax.CountryStateZip/CountryStateZipTaxProvider.cs
@@ -15,18 +15,18 @@ public class CountryStateZipTaxProvider : ITaxProvider
private readonly CountryStateZipTaxSettings _countryStateZipTaxSettings;
private readonly ITaxRateService _taxRateService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public CountryStateZipTaxProvider(ITranslationService translationService,
ICacheBase cacheBase,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ITaxRateService taxRateService,
CountryStateZipTaxSettings countryStateZipTaxSettings)
{
_translationService = translationService;
_cacheBase = cacheBase;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_taxRateService = taxRateService;
_countryStateZipTaxSettings = countryStateZipTaxSettings;
}
@@ -74,7 +74,7 @@ public class CountryStateZipTaxProvider : ITaxProvider
});
});
- var storeId = _workContext.CurrentStore.Id;
+ var storeId = _workContextAccessor.WorkContext.CurrentStore.Id;
var taxCategoryId = calculateTaxRequest.TaxCategoryId;
var countryId = calculateTaxRequest.Address.CountryId;
var stateProvinceId = calculateTaxRequest.Address.StateProvinceId;
diff --git a/src/Plugins/Theme.Modern/Views/Modern/Blog/BlogPost.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Blog/BlogPost.cshtml
index 6d59670aa..a2b361849 100644
--- a/src/Plugins/Theme.Modern/Views/Modern/Blog/BlogPost.cshtml
+++ b/src/Plugins/Theme.Modern/Views/Modern/Blog/BlogPost.cshtml
@@ -1,5 +1,5 @@
@model BlogPostModel
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@inject IPageHeadBuilder pagebuilder
@{
Layout = "_TwoColumns";
diff --git a/src/Plugins/Theme.Modern/Views/Modern/Blog/List.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Blog/List.cshtml
index 8e6b53965..6eb1ac864 100644
--- a/src/Plugins/Theme.Modern/Views/Modern/Blog/List.cshtml
+++ b/src/Plugins/Theme.Modern/Views/Modern/Blog/List.cshtml
@@ -1,5 +1,5 @@
@model BlogPostListModel
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@inject IPageHeadBuilder pagebuilder
@{
Layout = "_TwoColumns";
diff --git a/src/Plugins/Theme.Modern/Views/Modern/Checkout/Completed.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Checkout/Completed.cshtml
index d770323f9..8edd1e756 100644
--- a/src/Plugins/Theme.Modern/Views/Modern/Checkout/Completed.cshtml
+++ b/src/Plugins/Theme.Modern/Views/Modern/Checkout/Completed.cshtml
@@ -1,4 +1,4 @@
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@model CheckoutCompletedModel
@{
diff --git a/src/Plugins/Theme.Modern/Views/Modern/Product/ProductLayout.Simple.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Product/ProductLayout.Simple.cshtml
index b69ada3ed..dfc1aaf83 100644
--- a/src/Plugins/Theme.Modern/Views/Modern/Product/ProductLayout.Simple.cshtml
+++ b/src/Plugins/Theme.Modern/Views/Modern/Product/ProductLayout.Simple.cshtml
@@ -1,6 +1,6 @@
@model ProductDetailsModel
@inject SeoSettings seoSettings
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@inject IPageHeadBuilder pagebuilder
@{
diff --git a/src/Plugins/Theme.Modern/Views/Modern/Shared/Components/SearchBox/Default.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Shared/Components/SearchBox/Default.cshtml
index 15a4a221f..45bb47e34 100644
--- a/src/Plugins/Theme.Modern/Views/Modern/Shared/Components/SearchBox/Default.cshtml
+++ b/src/Plugins/Theme.Modern/Views/Modern/Shared/Components/SearchBox/Default.cshtml
@@ -1,9 +1,9 @@
@using Grand.Domain.Blogs
@model SearchBoxModel
@inject BlogSettings blogSettings
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@{
- var lang = workContext.WorkingLanguage.LanguageCulture;
+ var lang = workContextAccessor.WorkContext.WorkingLanguage.LanguageCulture;
}
<ul class="search-item">
<li>
diff --git a/src/Plugins/Theme.Modern/Views/Modern/Shared/Partials/Logo.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Shared/Partials/Logo.cshtml
index 403c2b2bf..4dcc0164f 100644
--- a/src/Plugins/Theme.Modern/Views/Modern/Shared/Partials/Logo.cshtml
+++ b/src/Plugins/Theme.Modern/Views/Modern/Shared/Partials/Logo.cshtml
@@ -1,11 +1,11 @@
@using Grand.Business.Core.Interfaces.Storage
@inject StoreInformationSettings storeInformation
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@inject IPictureService pictureService
@{
var urlLogo = await pictureService.GetPictureUrl(storeInformation.LogoPictureId);
}
<a class="navbar-brand store-logo" target="_self" href="@Url.RouteUrl("HomePage")">
- <img width="236" height="53" src="@urlLogo" alt="@workContext.CurrentStore.Name"/>
+ <img width="236" height="53" src="@urlLogo" alt="@workContextAccessor.WorkContext.CurrentStore.Name" />
<span class="sr-only">@Loc["Logo"]</span>
</a>
\ No newline at end of file
diff --git a/src/Plugins/Theme.Modern/Views/Modern/Shared/Partials/ShoppingCartLinks.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Shared/Partials/ShoppingCartLinks.cshtml
index 0c2739912..8d4c2da8c 100644
--- a/src/Plugins/Theme.Modern/Views/Modern/Shared/Partials/ShoppingCartLinks.cshtml
+++ b/src/Plugins/Theme.Modern/Views/Modern/Shared/Partials/ShoppingCartLinks.cshtml
@@ -2,7 +2,7 @@
@using Grand.Business.Core.Interfaces.Common.Security
@using Grand.Domain.Permissions
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@inject IPermissionService permissionService
@inject IShoppingCartService shoppingCartService
@@ -19,13 +19,13 @@
var wishlistEnabled = await permissionService.Authorize(StandardPermission.EnableWishlist);
var miniShoppingCartEnabled = shoppingCartSettings.MiniShoppingCartEnabled;
var shoppingCartItems =
- workContext.CurrentCustomer.ShoppingCartItems.Any()
- ? (await shoppingCartService.GetShoppingCart(workContext.CurrentStore.Id, shoppingCartTypes.ToArray()))
+ workContextAccessor.WorkContext.CurrentCustomer.ShoppingCartItems.Any()
+ ? (await shoppingCartService.GetShoppingCart(workContextAccessor.WorkContext.CurrentStore.Id, shoppingCartTypes.ToArray()))
.Sum(x => x.Quantity)
: 0;
- var wishlistItems = workContext.CurrentCustomer.ShoppingCartItems.Any()
- ? (await shoppingCartService.GetShoppingCart(workContext.CurrentStore.Id, ShoppingCartType.Wishlist))
+ var wishlistItems = workContextAccessor.WorkContext.CurrentCustomer.ShoppingCartItems.Any()
+ ? (await shoppingCartService.GetShoppingCart(workContextAccessor.WorkContext.CurrentStore.Id, ShoppingCartType.Wishlist))
.Sum(x => x.Quantity)
: 0;
}
diff --git a/src/Plugins/Widgets.FacebookPixel/Areas/Admin/Controllers/WidgetsFacebookPixelController.cs b/src/Plugins/Widgets.FacebookPixel/Areas/Admin/Controllers/WidgetsFacebookPixelController.cs
index 2da61bb36..596abaa0c 100644
--- a/src/Plugins/Widgets.FacebookPixel/Areas/Admin/Controllers/WidgetsFacebookPixelController.cs
+++ b/src/Plugins/Widgets.FacebookPixel/Areas/Admin/Controllers/WidgetsFacebookPixelController.cs
@@ -19,14 +19,14 @@ public class WidgetsFacebookPixelController : BaseAdminPluginController
private readonly ISettingService _settingService;
private readonly IStoreService _storeService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public WidgetsFacebookPixelController(IWorkContext workContext,
+ public WidgetsFacebookPixelController(IWorkContextAccessor workContextAccessor,
IStoreService storeService,
ISettingService settingService,
ITranslationService translationService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_storeService = storeService;
_settingService = settingService;
_translationService = translationService;
@@ -50,7 +50,7 @@ public class WidgetsFacebookPixelController : BaseAdminPluginController
public async Task<IActionResult> Configure()
{
//load settings for a chosen store scope
- var storeScope = await GetActiveStore(_storeService, _workContext);
+ var storeScope = await GetActiveStore(_storeService, _workContextAccessor.WorkContext);
var facebookPixelSettings = _settingService.LoadSetting<FacebookPixelSettings>(storeScope);
var model = new ConfigurationModel {
PixelId = facebookPixelSettings.PixelId,
@@ -71,7 +71,7 @@ public class WidgetsFacebookPixelController : BaseAdminPluginController
public async Task<IActionResult> Configure(ConfigurationModel model)
{
//load settings for a chosen store scope
- var storeScope = await GetActiveStore(_storeService, _workContext);
+ var storeScope = await GetActiveStore(_storeService, _workContextAccessor.WorkContext);
var facebookPixelSettings = _settingService.LoadSetting<FacebookPixelSettings>(storeScope);
facebookPixelSettings.PixelId = model.PixelId;
facebookPixelSettings.PixelScript = model.PixelScript;
diff --git a/src/Plugins/Widgets.FacebookPixel/Components/WidgetsFacebookPixelViewComponent.cs b/src/Plugins/Widgets.FacebookPixel/Components/WidgetsFacebookPixelViewComponent.cs
index 322e382a2..73d698c9f 100644
--- a/src/Plugins/Widgets.FacebookPixel/Components/WidgetsFacebookPixelViewComponent.cs
+++ b/src/Plugins/Widgets.FacebookPixel/Components/WidgetsFacebookPixelViewComponent.cs
@@ -14,16 +14,16 @@ public class WidgetsFacebookPixelViewComponent : ViewComponent
private readonly ICookiePreference _cookiePreference;
private readonly FacebookPixelSettings _facebookPixelSettings;
private readonly IOrderService _orderService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public WidgetsFacebookPixelViewComponent(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IOrderService orderService,
ICookiePreference cookiePreference,
FacebookPixelSettings facebookPixelSettings
)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_orderService = orderService;
_cookiePreference = cookiePreference;
_facebookPixelSettings = facebookPixelSettings;
@@ -33,7 +33,7 @@ public class WidgetsFacebookPixelViewComponent : ViewComponent
{
if (_facebookPixelSettings.AllowToDisableConsentCookie)
{
- var enabled = await _cookiePreference.IsEnable(_workContext.CurrentCustomer, _workContext.CurrentStore,
+ var enabled = await _cookiePreference.IsEnable(_workContextAccessor.WorkContext.CurrentCustomer, _workContextAccessor.WorkContext.CurrentStore,
FacebookPixelDefaults.ConsentCookieSystemName);
if ((enabled.HasValue && !enabled.Value) ||
(!enabled.HasValue && !_facebookPixelSettings.ConsentDefaultState))
@@ -75,7 +75,7 @@ public class WidgetsFacebookPixelViewComponent : ViewComponent
trackingScript = trackingScript.Replace("{QTY}", model.Quantity.ToString("N0"));
trackingScript =
trackingScript.Replace("{AMOUNT}", model.DecimalPrice.ToString("F2", CultureInfo.InvariantCulture));
- trackingScript = trackingScript.Replace("{CURRENCY}", _workContext.WorkingCurrency.CurrencyCode);
+ trackingScript = trackingScript.Replace("{CURRENCY}", _workContextAccessor.WorkContext.WorkingCurrency.CurrencyCode);
return trackingScript;
}
diff --git a/src/Plugins/Widgets.GoogleAnalytics/Areas/Admin/Controllers/WidgetsGoogleAnalyticsController.cs b/src/Plugins/Widgets.GoogleAnalytics/Areas/Admin/Controllers/WidgetsGoogleAnalyticsController.cs
index f651fffd2..57997944a 100644
--- a/src/Plugins/Widgets.GoogleAnalytics/Areas/Admin/Controllers/WidgetsGoogleAnalyticsController.cs
+++ b/src/Plugins/Widgets.GoogleAnalytics/Areas/Admin/Controllers/WidgetsGoogleAnalyticsController.cs
@@ -18,14 +18,14 @@ public class WidgetsGoogleAnalyticsController : BaseAdminPluginController
private readonly ISettingService _settingService;
private readonly IStoreService _storeService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public WidgetsGoogleAnalyticsController(IWorkContext workContext,
+ public WidgetsGoogleAnalyticsController(IWorkContextAccessor workContextAccessor,
IStoreService storeService,
ISettingService settingService,
ITranslationService translationService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_storeService = storeService;
_settingService = settingService;
_translationService = translationService;
@@ -48,7 +48,7 @@ public class WidgetsGoogleAnalyticsController : BaseAdminPluginController
public async Task<IActionResult> Configure()
{
//load settings for a chosen store scope
- var storeScope = await GetActiveStore(_storeService, _workContext);
+ var storeScope = await GetActiveStore(_storeService, _workContextAccessor.WorkContext);
var googleAnalyticsSettings = _settingService.LoadSetting<GoogleAnalyticsEcommerceSettings>(storeScope);
var model = new ConfigurationModel {
GoogleId = googleAnalyticsSettings.GoogleId,
@@ -70,7 +70,7 @@ public class WidgetsGoogleAnalyticsController : BaseAdminPluginController
public async Task<IActionResult> Configure(ConfigurationModel model)
{
//load settings for a chosen store scope
- var storeScope = await GetActiveStore(_storeService, _workContext);
+ var storeScope = await GetActiveStore(_storeService, _workContextAccessor.WorkContext);
var googleAnalyticsSettings = _settingService.LoadSetting<GoogleAnalyticsEcommerceSettings>(storeScope);
googleAnalyticsSettings.GoogleId = model.GoogleId;
googleAnalyticsSettings.TrackingScript = model.TrackingScript;
diff --git a/src/Plugins/Widgets.GoogleAnalytics/Components/WidgetsGoogleAnalyticsViewComponent.cs b/src/Plugins/Widgets.GoogleAnalytics/Components/WidgetsGoogleAnalyticsViewComponent.cs
index 1fff52f61..7512c82d5 100644
--- a/src/Plugins/Widgets.GoogleAnalytics/Components/WidgetsGoogleAnalyticsViewComponent.cs
+++ b/src/Plugins/Widgets.GoogleAnalytics/Components/WidgetsGoogleAnalyticsViewComponent.cs
@@ -20,15 +20,15 @@ public class WidgetsGoogleAnalyticsViewComponent : ViewComponent
private readonly GoogleAnalyticsEcommerceSettings _googleAnalyticsEcommerceSettings;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ILogger<WidgetsGoogleAnalyticsViewComponent> _logger;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public WidgetsGoogleAnalyticsViewComponent(IWorkContext workContext,
+ public WidgetsGoogleAnalyticsViewComponent(IWorkContextAccessor workContextAccessor,
ILogger<WidgetsGoogleAnalyticsViewComponent> logger,
GoogleAnalyticsEcommerceSettings googleAnalyticsEcommerceSettings,
ICookiePreference cookiePreference,
IHttpContextAccessor httpContextAccessor)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_logger = logger;
_googleAnalyticsEcommerceSettings = googleAnalyticsEcommerceSettings;
_cookiePreference = cookiePreference;
@@ -41,7 +41,7 @@ public class WidgetsGoogleAnalyticsViewComponent : ViewComponent
if (_googleAnalyticsEcommerceSettings.AllowToDisableConsentCookie)
{
- var enabled = await _cookiePreference.IsEnable(_workContext.CurrentCustomer, _workContext.CurrentStore,
+ var enabled = await _cookiePreference.IsEnable(_workContextAccessor.WorkContext.CurrentCustomer, _workContextAccessor.WorkContext.CurrentStore,
GoogleAnalyticDefaults.ConsentCookieSystemName);
if ((enabled.HasValue && !enabled.Value) ||
(!enabled.HasValue && !_googleAnalyticsEcommerceSettings.ConsentDefaultState))
@@ -80,8 +80,8 @@ public class WidgetsGoogleAnalyticsViewComponent : ViewComponent
private async Task<Order> GetLastOrder()
{
var orderService = _httpContextAccessor.HttpContext!.RequestServices.GetRequiredService<IOrderService>();
- var order = (await orderService.SearchOrders(_workContext.CurrentStore.Id,
- customerId: _workContext.CurrentCustomer.Id, pageSize: 1)).FirstOrDefault();
+ var order = (await orderService.SearchOrders(_workContextAccessor.WorkContext.CurrentStore.Id,
+ customerId: _workContextAccessor.WorkContext.CurrentCustomer.Id, pageSize: 1)).FirstOrDefault();
return order;
}
diff --git a/src/Plugins/Widgets.Slider/Components/WidgetSliderComponent.cs b/src/Plugins/Widgets.Slider/Components/WidgetSliderComponent.cs
index 37ded1502..a3100a3e0 100644
--- a/src/Plugins/Widgets.Slider/Components/WidgetSliderComponent.cs
+++ b/src/Plugins/Widgets.Slider/Components/WidgetSliderComponent.cs
@@ -13,16 +13,16 @@ public class WidgetSliderComponent : ViewComponent
{
private readonly IPictureService _pictureService;
private readonly ISliderService _sliderService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public WidgetSliderComponent(
IPictureService pictureService,
ISliderService sliderService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_pictureService = pictureService;
_sliderService = sliderService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
private async Task<string> GetPictureUrl(string pictureId)
@@ -44,8 +44,8 @@ public class WidgetSliderComponent : ViewComponent
model.Slide.Add(new PublicInfoModel.Slider {
Link = item.Link,
PictureUrl = await GetPictureUrl(item.PictureId),
- Name = item.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- Description = item.GetTranslation(x => x.Description, _workContext.WorkingLanguage.Id),
+ Name = item.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Description = item.GetTranslation(x => x.Description, _workContextAccessor.WorkContext.WorkingLanguage.Id),
FullWidth = item.FullWidth,
CssClass = i == 1 ? "active" : ""
});
diff --git a/src/Plugins/Widgets.Slider/Services/SliderService.cs b/src/Plugins/Widgets.Slider/Services/SliderService.cs
index 405faeb63..d4ce6e5be 100644
--- a/src/Plugins/Widgets.Slider/Services/SliderService.cs
+++ b/src/Plugins/Widgets.Slider/Services/SliderService.cs
@@ -9,11 +9,11 @@ namespace Widgets.Slider.Services;
public class SliderService : ISliderService
{
public SliderService(IRepository<PictureSlider> repositoryPictureSlider,
- IWorkContext workContext, IAclService aclService,
+ IWorkContextAccessor workContextAccessor, IAclService aclService,
ICacheBase cacheManager)
{
_repositoryPictureSlider = repositoryPictureSlider;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_aclService = aclService;
_cacheBase = cacheManager;
}
@@ -48,7 +48,7 @@ public class SliderService : ISliderService
/// <returns>Picture Sliders</returns>
public virtual async Task<IList<PictureSlider>> GetPictureSliders(SliderType sliderType, string objectEntry = "")
{
- var cacheKey = string.Format(SLIDERS_MODEL_KEY, _workContext.CurrentStore.Id, sliderType.ToString(),
+ var cacheKey = string.Format(SLIDERS_MODEL_KEY, _workContextAccessor.WorkContext.CurrentStore.Id, sliderType.ToString(),
objectEntry);
return await _cacheBase.GetAsync(cacheKey, async () =>
{
@@ -60,7 +60,7 @@ public class SliderService : ISliderService
query = query.Where(x => x.ObjectEntry == objectEntry);
var items = query.ToList();
- return await Task.FromResult(items.Where(c => _aclService.Authorize(c, _workContext.CurrentStore.Id))
+ return await Task.FromResult(items.Where(c => _aclService.Authorize(c, _workContextAccessor.WorkContext.CurrentStore.Id))
.ToList());
});
}
@@ -122,7 +122,7 @@ public class SliderService : ISliderService
private readonly IRepository<PictureSlider> _repositoryPictureSlider;
private readonly IAclService _aclService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ICacheBase _cacheBase;
/// <summary>
diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs
index 59bb38ee5..c920a6ae5 100644
--- a/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs
+++ b/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs
@@ -25,7 +25,7 @@ public class ExternalAuthenticationServiceTests
private ExternalAuthenticationService _externalAuthenticationService;
private Mock<IGroupService> _groupServiceMock;
private Mock<IMediator> _mediatorMock;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
@@ -36,7 +36,9 @@ public class ExternalAuthenticationServiceTests
_customerManagerServiceMock = new Mock<ICustomerManagerService>();
_mediatorMock = new Mock<IMediator>();
_externalAuthenticationRecordRepository = new MongoDBRepositoryTest<ExternalAuthentication>();
- _workContextMock = new Mock<IWorkContext>();
+ _workContextMock = new Mock<IWorkContextAccessor>();
+ _workContextMock.Setup(s => s.WorkContext.CurrentCustomer).Returns(new Customer());
+
_externalAuthenticationProviders = new List<IExternalAuthenticationProvider>
{ new ExternalAuthenticationProviderTest() };
diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs
index ddd33f5c0..d24f3fa04 100644
--- a/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs
+++ b/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs
@@ -17,12 +17,12 @@ public class TwoFactorAuthenticationServiceTests
private Mock<IEnumerable<ISMSVerificationService>> _sMsVerificationService;
private TwoFactorAuthenticationService _twoFactorAuthenticationService;
private Mock<ICustomerService> _customerServiceMock;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
{
- _workContextMock = new Mock<IWorkContext>();
+ _workContextMock = new Mock<IWorkContextAccessor>();
_customerServiceMock = new Mock<ICustomerService>();
_sMsVerificationService = new Mock<IEnumerable<ISMSVerificationService>>();
_twoFactorAuthenticationService = new TwoFactorAuthenticationService(_workContextMock.Object,
@@ -33,8 +33,8 @@ public class TwoFactorAuthenticationServiceTests
public async Task GenerateCodeSetupTest_AppVerification()
{
//Arrange
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
//Act
var result = await _twoFactorAuthenticationService.GenerateCodeSetup(Guid.NewGuid().ToString(),
new Customer { Email = "[email protected]" },
@@ -48,8 +48,8 @@ public class TwoFactorAuthenticationServiceTests
public async Task GenerateCodeSetupTest_Email()
{
//Arrange
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
//Act
var result = await _twoFactorAuthenticationService.GenerateCodeSetup(Guid.NewGuid().ToString(),
new Customer { Email = "[email protected]" },
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Brands/BrandServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Brands/BrandServiceTests.cs
index ba6f4c9a9..5525386a1 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Brands/BrandServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Brands/BrandServiceTests.cs
@@ -8,7 +8,6 @@ using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Tests.Caching;
-using Grand.SharedKernel.Extensions;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
@@ -22,15 +21,15 @@ public class BrandServiceTests
private MemoryCacheBase _cacheBase;
private Mock<IMediator> _mediatorMock;
private IRepository<Brand> _repository;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void InitializeTests()
{
_repository = new MongoDBRepositoryTest<Brand>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock = new Mock<IWorkContextAccessor>();
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
_mediatorMock = new Mock<IMediator>();
_cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
new CacheConfig { DefaultCacheTimeMinutes = 1 });
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceDbTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceDbTests.cs
index 28e9bd408..d7231ef52 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceDbTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceDbTests.cs
@@ -26,15 +26,15 @@ public class CategoryServiceDbTests
private CategoryService _categoryService;
private Mock<IMediator> _mediatorMock;
private CatalogSettings _settings;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void InitializeTests()
{
_categoryRepository = new MongoDBRepositoryTest<Category>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock = new Mock<IWorkContextAccessor>();
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
_mediatorMock = new Mock<IMediator>();
_aclServiceMock = new AclService(new AccessControlConfig());
_settings = new CatalogSettings();
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceTests.cs
index 579bf6176..d0930fd5a 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceTests.cs
@@ -28,7 +28,7 @@ public class CategoryServiceTests
private ProductCategoryService _productCategoryService;
private Mock<MongoRepository<Product>> _productRepositoryMock;
private CatalogSettings _settings;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
@@ -38,7 +38,7 @@ public class CategoryServiceTests
_casheManagerMock = new Mock<ICacheBase>();
_categoryRepositoryMock = new Mock<IRepository<Category>>();
_productRepositoryMock = new Mock<MongoRepository<Product>>(Mock.Of<IAuditInfoProvider>());
- _workContextMock = new Mock<IWorkContext>();
+ _workContextMock = new Mock<IWorkContextAccessor>();
_mediatorMock = new Mock<IMediator>();
_aclServiceMock = new Mock<IAclService>();
_settings = new CatalogSettings();
@@ -98,7 +98,7 @@ public class CategoryServiceTests
{
var allCategory = GetMockCategoryList();
var category = new Category { Id = "6", ParentCategoryId = "3", Published = true };
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "" });
_aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<Customer>())).Returns(() => true);
_aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<string>())).Returns(() => true);
var result = _categoryService.GetCategoryBreadCrumb(category, allCategory);
@@ -112,7 +112,7 @@ public class CategoryServiceTests
{
var allCategory = GetMockCategoryList();
var category = new Category { Id = "6", ParentCategoryId = "1", Published = true };
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "" });
_aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<Customer>())).Returns(() => true);
_aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<string>())).Returns(() => true);
var result = _categoryService.GetCategoryBreadCrumb(category, allCategory);
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/ProductCategoryServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/ProductCategoryServiceTests.cs
index 934fe004c..d6e507c15 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/ProductCategoryServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/ProductCategoryServiceTests.cs
@@ -22,15 +22,15 @@ public class ProductCategoryServiceTests
private Mock<IMediator> _mediatorMock;
private ProductCategoryService _productCategoryService;
private IRepository<Product> _repository;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void InitializeTests()
{
_repository = new MongoDBRepositoryTest<Product>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock = new Mock<IWorkContextAccessor>();
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
_mediatorMock = new Mock<IMediator>();
_cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
new CacheConfig { DefaultCacheTimeMinutes = 1 });
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/CollectionServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/CollectionServiceTests.cs
index 18a483e6c..431fd6abf 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/CollectionServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/CollectionServiceTests.cs
@@ -22,14 +22,14 @@ public class CollectionServiceTests
private Mock<IMediator> _mediatorMock;
private Mock<IRepository<Collection>> _repositoryMock;
private CatalogSettings _settings;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
{
_cacheMock = new Mock<ICacheBase>();
_repositoryMock = new Mock<IRepository<Collection>>();
- _workContextMock = new Mock<IWorkContext>();
+ _workContextMock = new Mock<IWorkContextAccessor>();
_mediatorMock = new Mock<IMediator>();
_aclMock = new Mock<IAclService>();
_settings = new CatalogSettings();
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/ProductCollectionServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/ProductCollectionServiceTests.cs
index cf35316b7..2fa0601b0 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/ProductCollectionServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/ProductCollectionServiceTests.cs
@@ -22,15 +22,15 @@ public class ProductCollectionServiceTests
private Mock<IMediator> _mediatorMock;
private ProductCollectionService _productCollectionService;
private IRepository<Product> _repository;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void InitializeTests()
{
_repository = new MongoDBRepositoryTest<Product>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock = new Mock<IWorkContextAccessor>();
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
_mediatorMock = new Mock<IMediator>();
_cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
new CacheConfig { DefaultCacheTimeMinutes = 1 });
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/BrandImportDataObjectTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/BrandImportDataObjectTests.cs
index 19864a2f2..87b68bcbf 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/BrandImportDataObjectTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/BrandImportDataObjectTests.cs
@@ -40,7 +40,7 @@ public class BrandImportDataObjectTests
private IRepository<Brand> _repository;
private Mock<ISlugService> _slugServiceMock;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
private ISeNameService _seNameService;
[TestInitialize]
public void Init()
@@ -53,9 +53,9 @@ public class BrandImportDataObjectTests
_brandLayoutServiceMock = new Mock<IBrandLayoutService>();
_slugServiceMock = new Mock<ISlugService>();
_languageServiceMock = new Mock<ILanguageService>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock = new Mock<IWorkContextAccessor>();
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
_mediatorMock = new Mock<IMediator>();
_cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CategoryImportDataObjectTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CategoryImportDataObjectTests.cs
index 2596be03b..b978410bc 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CategoryImportDataObjectTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CategoryImportDataObjectTests.cs
@@ -41,7 +41,7 @@ public class CategoryImportDataObjectTests
private IRepository<Category> _repository;
private Mock<ISlugService> _slugServiceMock;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
private ISeNameService _seNameService;
[TestInitialize]
public void Init()
@@ -54,9 +54,9 @@ public class CategoryImportDataObjectTests
_categoryLayoutServiceMock = new Mock<ICategoryLayoutService>();
_slugServiceMock = new Mock<ISlugService>();
_languageServiceMock = new Mock<ILanguageService>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock = new Mock<IWorkContextAccessor>();
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
_mediatorMock = new Mock<IMediator>();
_cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CollectionImportDataObjectTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CollectionImportDataObjectTests.cs
index 48783e68e..645a261cc 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CollectionImportDataObjectTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CollectionImportDataObjectTests.cs
@@ -41,7 +41,7 @@ public class CollectionImportDataObjectTests
private IRepository<Collection> _repository;
private Mock<ISlugService> _slugServiceMock;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
private ISeNameService _seNameService;
[TestInitialize]
public void Init()
@@ -54,9 +54,9 @@ public class CollectionImportDataObjectTests
_collectionLayoutServiceMock = new Mock<ICollectionLayoutService>();
_slugServiceMock = new Mock<ISlugService>();
_languageServiceMock = new Mock<ILanguageService>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock = new Mock<IWorkContextAccessor>();
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
_mediatorMock = new Mock<IMediator>();
_cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/ProductImportDataObjectTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/ProductImportDataObjectTests.cs
index e090ae42c..668365d8d 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/ProductImportDataObjectTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/ProductImportDataObjectTests.cs
@@ -59,7 +59,7 @@ public class ProductImportDataObjectTests
private Mock<ISlugService> _slugServiceMock;
private Mock<ITaxCategoryService> _taxServiceMock;
private Mock<IWarehouseService> _warehouseServiceMock;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
private ISeNameService _seNameService;
[TestInitialize]
public void Init()
@@ -82,9 +82,9 @@ public class ProductImportDataObjectTests
_productCategoryServiceMock = new Mock<IProductCategoryService>();
_productCollectionServiceMock = new Mock<IProductCollectionService>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock = new Mock<IWorkContextAccessor>();
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
_mediatorMock = new Mock<IMediator>();
_cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceFormatterTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceFormatterTests.cs
index 27d3d11bd..1acc4ad27 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceFormatterTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceFormatterTests.cs
@@ -32,8 +32,7 @@ public class PriceFormatterTests
private TaxSettings _taxSettings;
private ITranslationService _translationService;
- private IWorkContext _workContext;
- private Mock<IWorkContext> tempWorkContext;
+ private Mock<IWorkContextAccessor> tempWorkContext;
[TestInitialize]
public void TestInitialize()
@@ -45,10 +44,8 @@ public class PriceFormatterTests
_eventPublisher = eventPublisher.Object;
var cacheManager = new Mock<ICacheBase>();
- tempWorkContext = new Mock<IWorkContext>();
- {
- _workContext = tempWorkContext.Object;
- }
+ tempWorkContext = new Mock<IWorkContextAccessor>();
+
_currencySettings = new CurrencySettings();
var currency01 = new Currency {
Id = "1",
@@ -102,7 +99,7 @@ public class PriceFormatterTests
_translationService = tempLocalizationService.Object;
}
- _priceFormatter = new PriceFormatter(_workContext);
+ _priceFormatter = new PriceFormatter(tempWorkContext.Object);
}
[TestMethod]
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.cs
index f26458c95..a7401b9b9 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.cs
@@ -44,10 +44,10 @@ public class PriceServiceTests
private IProductService _productService;
private ShoppingCartSettings _shoppingCartSettings;
private Store _store;
- private IWorkContext _workContext;
+ private IWorkContextAccessor _workContext;
private Mock<IDiscountService> tempDiscountServiceMock;
private Mock<IProductService> tempProductService;
- private Mock<IWorkContext> tempWorkContext;
+ private Mock<IWorkContextAccessor> tempWorkContext;
[TestInitialize]
public void TestInitialize()
@@ -56,10 +56,10 @@ public class PriceServiceTests
DataSettingsManager.Initialize(settingsPath);
_store = new Store { Id = "1" };
- tempWorkContext = new Mock<IWorkContext>();
+ tempWorkContext = new Mock<IWorkContextAccessor>();
{
- tempWorkContext.Setup(instance => instance.WorkingCurrency).Returns(_currency);
- tempWorkContext.Setup(c => c.CurrentStore).Returns(_store);
+ tempWorkContext.Setup(instance => instance.WorkContext.WorkingCurrency).Returns(_currency);
+ tempWorkContext.Setup(c => c.WorkContext.CurrentStore).Returns(_store);
_workContext = tempWorkContext.Object;
}
@@ -282,8 +282,8 @@ public class PriceServiceTests
public async Task Can_get_shopping_cart_item_unitPrice()
{
var customer001 = new Customer { Id = "98767" };
- tempWorkContext.Setup(x => x.CurrentCustomer).Returns(customer001);
- tempWorkContext.Setup(x => x.WorkingCurrency).Returns(_currency);
+ tempWorkContext.Setup(x => x.WorkContext.CurrentCustomer).Returns(customer001);
+ tempWorkContext.Setup(x => x.WorkContext.WorkingCurrency).Returns(_currency);
var product001 = new Product {
Id = "242422",
Name = "product name 01",
@@ -329,8 +329,8 @@ public class PriceServiceTests
tempProductService.Setup(x => x.GetProductById("242422", false)).ReturnsAsync(product001);
var customer001 = new Customer { Id = "98767" };
- tempWorkContext.Setup(x => x.CurrentCustomer).Returns(customer001);
- tempWorkContext.Setup(x => x.WorkingCurrency).Returns(_currency);
+ tempWorkContext.Setup(x => x.WorkContext.CurrentCustomer).Returns(customer001);
+ tempWorkContext.Setup(x => x.WorkContext.WorkingCurrency).Returns(_currency);
var shoppingCartItem = new ShoppingCartItem {
ProductId = product001.Id, //222
Quantity = 2
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeFormatterTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeFormatterTests.cs
index 5cb2dd7a4..2082186e8 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeFormatterTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeFormatterTests.cs
@@ -30,14 +30,14 @@ public class ProductAttributeFormatterTests
private Mock<IProductService> _productServiceMock;
private Mock<ITaxService> _taxServiceMock;
private Mock<ITranslationService> _translationServiceMock;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void InitializeTests()
{
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock = new Mock<IWorkContextAccessor>();
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
_productAttributeServiceMock = new Mock<IProductAttributeService>();
_productAttributeServiceMock.Setup(x => x.GetProductAttributeById(It.IsAny<string>()))
.Returns(Task.FromResult(new ProductAttribute { Name = "test" }));
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.cs
index 74462ff25..553deaff1 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.cs
@@ -27,15 +27,15 @@ public class ProductServiceTests
private Mock<IMediator> _mediatorMock;
private IRepository<Product> _productRepository;
private ProductService _productService;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void InitializeTests()
{
_productRepository = new MongoDBRepositoryTest<Product>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock = new Mock<IWorkContextAccessor>();
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
_mediatorMock = new Mock<IMediator>();
_mediatorMock.Setup(x => x.Send(It.IsAny<GetProductArchByIdQuery>(), default))
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs
index 8f4e9f9f5..0eb3ff876 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs
@@ -29,7 +29,7 @@ public class TaxServiceTests
private TaxSettings _taxSettings;
private IVatService _vatService;
- private IWorkContext _workContext;
+ private IWorkContextAccessor _workContext;
[TestInitialize]
public void TestInitialize()
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/CustomerLoggedInEventHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/CustomerLoggedInEventHandlerTests.cs
index 0da4fbdbd..903013348 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/CustomerLoggedInEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/CustomerLoggedInEventHandlerTests.cs
@@ -13,13 +13,15 @@ public class CustomerLoggedInEventHandlerTests
{
private CustomerLoggedInEventHandler _customerLoggedInEventHandler;
private Mock<IShoppingCartService> _shoppingCartServiceMock;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
{
_shoppingCartServiceMock = new Mock<IShoppingCartService>();
- _workContextMock = new Mock<IWorkContext>();
+ _workContextMock = new Mock<IWorkContextAccessor>();
+ _workContextMock.Setup(s => s.WorkContext.CurrentCustomer).Returns(new Customer());
+
_customerLoggedInEventHandler =
new CustomerLoggedInEventHandler(_shoppingCartServiceMock.Object, _workContextMock.Object);
}
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeParserTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeParserTests.cs
index 4c70f243f..ad2df3131 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeParserTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeParserTests.cs
@@ -23,7 +23,7 @@ public class CheckoutAttributeParserTests
private IRepository<CheckoutAttribute> _checkoutAttributeRepo;
private ICheckoutAttributeService _checkoutAttributeService;
private IMediator _eventPublisher;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
private CheckoutAttribute ca1, ca2, ca3;
private Mock<ICacheBase> cacheManager;
@@ -119,7 +119,7 @@ public class CheckoutAttributeParserTests
}
cacheManager = new Mock<ICacheBase>();
- _workContextMock = new Mock<IWorkContext>();
+ _workContextMock = new Mock<IWorkContextAccessor>();
_checkoutAttributeService = new CheckoutAttributeService(cacheManager.Object, _checkoutAttributeRepo,
_eventPublisher, _workContextMock.Object, new AccessControlConfig());
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeServiceTests.cs
index 67ddaee15..f43d7dae2 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeServiceTests.cs
@@ -19,7 +19,7 @@ public class CheckoutAttributeServiceTests
private Mock<IMediator> _mediatorMock;
private Mock<IRepository<CheckoutAttribute>> _repositoryMock;
private ICheckoutAttributeService _service;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
@@ -27,7 +27,7 @@ public class CheckoutAttributeServiceTests
_cacheMock = new Mock<ICacheBase>();
_repositoryMock = new Mock<IRepository<CheckoutAttribute>>();
_mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
+ _workContextMock = new Mock<IWorkContextAccessor>();
_service = new CheckoutAttributeService(_cacheMock.Object, _repositoryMock.Object, _mediatorMock.Object,
_workContextMock.Object, new AccessControlConfig());
}
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.cs
index 4670e196b..4f074c55e 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.cs
@@ -46,12 +46,12 @@ public class OrderCalculationServiceTests
private Mock<ITaxService> _taxServiceMock;
private TaxSettings _taxSettings;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
{
- _workContextMock = new Mock<IWorkContext>();
+ _workContextMock = new Mock<IWorkContextAccessor>();
_pricingServiceMock = new Mock<IPricingService>();
_taxServiceMock = new Mock<ITaxService>();
_shippingServiceMock = new Mock<IShippingService>();
@@ -69,12 +69,12 @@ public class OrderCalculationServiceTests
_shoppingCartSettings = new ShoppingCartSettings();
_catalogSettings = new CatalogSettings();
_discountValidationService = new Mock<IDiscountValidationService>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
var customer = new Customer();
customer.Groups.Add("1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
- _workContextMock.Setup(c => c.WorkingCurrency).Returns(() => new Currency());
- _workContextMock.Setup(c => c.TaxDisplayType).Returns(() => TaxDisplayType.ExcludingTax);
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => customer);
+ _workContextMock.Setup(c => c.WorkContext.WorkingCurrency).Returns(() => new Currency());
+ _workContextMock.Setup(c => c.WorkContext.TaxDisplayType).Returns(() => TaxDisplayType.ExcludingTax);
_service = new OrderCalculationService(_workContextMock.Object, _pricingServiceMock.Object,
_taxServiceMock.Object, _shippingServiceMock.Object,
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/ShoppingCartServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/ShoppingCartServiceTests.cs
index 19ef4f48f..15936454b 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/ShoppingCartServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/ShoppingCartServiceTests.cs
@@ -27,24 +27,24 @@ public class ShoppingCartServiceTests
private ShoppingCartService _shoppingCartService;
private ShoppingCartSettings _shoppingCartSettings;
private Mock<IShoppingCartValidator> _shoppingCartValidatorMock;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
{
- _workContextMock = new Mock<IWorkContext>();
+ _workContextMock = new Mock<IWorkContextAccessor>();
_productServiceMock = new Mock<IProductService>();
_shoppingCartSettings = new ShoppingCartSettings();
_customerServiceMock = new Mock<ICustomerService>();
_mediatorMock = new Mock<IMediator>();
_shoppingCartValidatorMock = new Mock<IShoppingCartValidator>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
var customer = new Customer();
customer.Groups.Add("1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
- _workContextMock.Setup(c => c.WorkingCurrency).Returns(() => new Currency());
- _workContextMock.Setup(c => c.TaxDisplayType).Returns(() => TaxDisplayType.ExcludingTax);
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => customer);
+ _workContextMock.Setup(c => c.WorkContext.WorkingCurrency).Returns(() => new Currency());
+ _workContextMock.Setup(c => c.WorkContext.TaxDisplayType).Returns(() => TaxDisplayType.ExcludingTax);
_shoppingCartService = new ShoppingCartService(_workContextMock.Object, _productServiceMock.Object,
_customerServiceMock.Object, _mediatorMock.Object, _shoppingCartValidatorMock.Object, _shoppingCartSettings);
@@ -58,7 +58,7 @@ public class ShoppingCartServiceTests
customer.Groups.Add("1");
customer.ShoppingCartItems.Add(new ShoppingCartItem
{ ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => customer);
_productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
@@ -79,7 +79,7 @@ public class ShoppingCartServiceTests
{ ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "", ProductId = "1" });
customer.ShoppingCartItems.Add(new ShoppingCartItem
{ ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "", ProductId = "2" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => customer);
_productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
@@ -98,7 +98,7 @@ public class ShoppingCartServiceTests
//Arrange
var customer = new Customer();
customer.Groups.Add("1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => customer);
_productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
@@ -123,7 +123,7 @@ public class ShoppingCartServiceTests
//Arrange
var customer = new Customer();
customer.Groups.Add("1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => customer);
_productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
@@ -148,7 +148,7 @@ public class ShoppingCartServiceTests
//Arrange
var customer = new Customer();
customer.Groups.Add("1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => customer);
_productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
@@ -175,7 +175,7 @@ public class ShoppingCartServiceTests
//Arrange
var customer = new Customer();
customer.Groups.Add("1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => customer);
_productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
@@ -201,7 +201,7 @@ public class ShoppingCartServiceTests
//Arrange
var customer = new Customer();
customer.Groups.Add("1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => customer);
_productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
diff --git a/src/Tests/Grand.Business.Cms.Tests/Services/KnowledgebaseServiceTests.cs b/src/Tests/Grand.Business.Cms.Tests/Services/KnowledgebaseServiceTests.cs
index 58b9b211d..d7790e612 100644
--- a/src/Tests/Grand.Business.Cms.Tests/Services/KnowledgebaseServiceTests.cs
+++ b/src/Tests/Grand.Business.Cms.Tests/Services/KnowledgebaseServiceTests.cs
@@ -25,7 +25,7 @@ public class KnowledgebaseServiceTests
private IRepository<KnowledgebaseArticleComment> _repositoryKnowledgebaseArticleComment;
private IRepository<KnowledgebaseCategory> _repositoryKnowledgebaseCategory;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
@@ -35,10 +35,10 @@ public class KnowledgebaseServiceTests
_repositoryKnowledgebaseArticleComment = new MongoDBRepositoryTest<KnowledgebaseArticleComment>();
_mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
+ _workContextMock = new Mock<IWorkContextAccessor>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
_cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
new CacheConfig { DefaultCacheTimeMinutes = 1 });
diff --git a/src/Tests/Grand.Business.Cms.Tests/Services/NewsServiceTests.cs b/src/Tests/Grand.Business.Cms.Tests/Services/NewsServiceTests.cs
index 206d28c71..fd6029846 100644
--- a/src/Tests/Grand.Business.Cms.Tests/Services/NewsServiceTests.cs
+++ b/src/Tests/Grand.Business.Cms.Tests/Services/NewsServiceTests.cs
@@ -19,7 +19,7 @@ public class NewsServiceTests
private NewsService _newsService;
private IRepository<NewsItem> _repository;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
@@ -27,10 +27,10 @@ public class NewsServiceTests
_repository = new MongoDBRepositoryTest<NewsItem>();
_mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
+ _workContextMock = new Mock<IWorkContextAccessor>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
_newsService = new NewsService(_repository, _mediatorMock.Object, _workContextMock.Object,
new AccessControlConfig());
diff --git a/src/Tests/Grand.Business.Cms.Tests/Services/PageServiceTests.cs b/src/Tests/Grand.Business.Cms.Tests/Services/PageServiceTests.cs
index db97141f2..5bdd08bff 100644
--- a/src/Tests/Grand.Business.Cms.Tests/Services/PageServiceTests.cs
+++ b/src/Tests/Grand.Business.Cms.Tests/Services/PageServiceTests.cs
@@ -25,7 +25,7 @@ public class PageServiceTests
private PageService _pageService;
private IRepository<Page> _repository;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
@@ -33,15 +33,15 @@ public class PageServiceTests
_repository = new MongoDBRepositoryTest<Page>();
_mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
+ _workContextMock = new Mock<IWorkContextAccessor>();
_cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
new CacheConfig { DefaultCacheTimeMinutes = 1 });
_aclService = new AclService(new AccessControlConfig());
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
_pageService = new PageService(_repository, _workContextMock.Object, _aclService, _mediatorMock.Object,
_cacheBase, new AccessControlConfig());
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Localization/TranslationServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Localization/TranslationServiceTests.cs
index cdd0751f5..612e8f7a9 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Localization/TranslationServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Localization/TranslationServiceTests.cs
@@ -18,7 +18,7 @@ public class TranslationServiceTests
private IRepository<TranslationResource> _repository;
private TranslationService _translationService;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
@@ -26,10 +26,10 @@ public class TranslationServiceTests
_repository = new MongoDBRepositoryTest<TranslationResource>();
_mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store());
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- _workContextMock.Setup(c => c.WorkingLanguage).Returns(() => new Language { Id = "1" });
+ _workContextMock = new Mock<IWorkContextAccessor>();
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store());
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock.Setup(c => c.WorkContext.WorkingLanguage).Returns(() => new Language { Id = "1" });
_translationService = new TranslationService(_workContextMock.Object, _repository, _mediatorMock.Object);
}
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Security/PermissionServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Security/PermissionServiceTests.cs
index b92003dc7..c73ba6dae 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Security/PermissionServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Security/PermissionServiceTests.cs
@@ -18,14 +18,14 @@ public class PermissionServiceTests
private Mock<IRepository<PermissionAction>> _permissionActionRepositoryMock;
private Mock<IRepository<Permission>> _permissionRepositoryMock;
private PermissionService _service;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
{
_permissionRepositoryMock = new Mock<IRepository<Permission>>();
_permissionActionRepositoryMock = new Mock<IRepository<PermissionAction>>();
- _workContextMock = new Mock<IWorkContext>();
+ _workContextMock = new Mock<IWorkContextAccessor>();
_groupServiceMock = new Mock<IGroupService>();
_cacheMock = new Mock<ICacheBase>();
_service = new PermissionService(_permissionRepositoryMock.Object, _permissionActionRepositoryMock.Object,
@@ -39,7 +39,7 @@ public class PermissionServiceTests
var permission = new Permission { SystemName = "permistion" };
var fakeCustomer = new Customer();
fakeCustomer.Groups.Add("group1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(fakeCustomer);
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(fakeCustomer);
_cacheMock.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<bool>>>()))
.Returns(Task.FromResult(true));
_groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
@@ -53,7 +53,7 @@ public class PermissionServiceTests
Permission permission = null;
var fakeCustomer = new Customer();
fakeCustomer.Groups.Add("group1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(fakeCustomer);
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(fakeCustomer);
_cacheMock.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<bool>>>()))
.Returns(Task.FromResult(true));
_groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Campaigns/CampaignServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Campaigns/CampaignServiceTests.cs
index 2e0b70226..aeead4633 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Campaigns/CampaignServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Campaigns/CampaignServiceTests.cs
@@ -29,7 +29,7 @@ public class CampaignServiceTests
private IRepository<NewsLetterSubscription> _newsLetterSubscriptionRepository;
private Mock<IQueuedEmailService> _queuedEmailServiceMock;
private Mock<IStoreService> _storeServiceMock;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
@@ -43,7 +43,7 @@ public class CampaignServiceTests
_queuedEmailServiceMock = new Mock<IQueuedEmailService>();
_storeServiceMock = new Mock<IStoreService>();
_languageServiceMock = new Mock<ILanguageService>();
- _workContextMock = new Mock<IWorkContext>();
+ _workContextMock = new Mock<IWorkContextAccessor>();
_campaignService = new CampaignService(_campaignRepository, _campaignHistoryRepository,
_newsLetterSubscriptionRepository, _customerRepository,
_emailSenderMock.Object, _queuedEmailServiceMock.Object, _storeServiceMock.Object, _mediatorMock.Object,
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeParserTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeParserTests.cs
index 2dbbe3604..98fb189f4 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeParserTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeParserTests.cs
@@ -18,14 +18,14 @@ public class ContactAttributeParserTests
private List<ContactAttribute> _contactAtr;
private Mock<IContactAttributeService> _contactAttributeServiceMock;
private ContactAttributeParser _parser;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
private List<CustomAttribute> customAtr;
[TestInitialize]
public void Init()
{
_contactAttributeServiceMock = new Mock<IContactAttributeService>();
- _workContextMock = new Mock<IWorkContext>();
+ _workContextMock = new Mock<IWorkContextAccessor>();
var _translationServiceMock = new Mock<ITranslationService>();
{
_translationServiceMock.Setup(x => x.GetResource(It.IsAny<string>())).Returns("Warning{0}");
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeServiceTests.cs
index e97d55313..c384ed429 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeServiceTests.cs
@@ -21,16 +21,16 @@ public class ContactAttributeServiceTests
private ContactAttributeService _contactAttributeService;
private Mock<IMediator> _mediatorMock;
private IRepository<ContactAttribute> _repository;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
{
_repository = new MongoDBRepositoryTest<ContactAttribute>();
_mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock = new Mock<IWorkContextAccessor>();
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => new Customer());
var accessControlConfig = new AccessControlConfig();
_cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
new CacheConfig { DefaultCacheTimeMinutes = 1 });
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerCoordinatesServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerCoordinatesServiceTests.cs
index fff2b518e..f2fc01701 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerCoordinatesServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerCoordinatesServiceTests.cs
@@ -18,17 +18,17 @@ public class CustomerCoordinatesServiceTests
private CustomerCoordinatesService _customerCoordinatesService;
private Mock<IMediator> _mediatorMock;
private IRepository<Customer> _repository;
- private Mock<IWorkContext> _workContextMock;
+ private Mock<IWorkContextAccessor> _workContextMock;
[TestInitialize]
public void Init()
{
_repository = new MongoDBRepositoryTest<Customer>();
_mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock = new Mock<IWorkContextAccessor>();
+ _workContextMock.Setup(c => c.WorkContext.CurrentStore).Returns(() => new Store { Id = "" });
_customer = new Customer();
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => _customer);
+ _workContextMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(() => _customer);
_customerCoordinatesService =
new CustomerCoordinatesService(_repository, _workContextMock.Object, _mediatorMock.Object);
@@ -80,8 +80,8 @@ public class CustomerCoordinatesServiceTests
//Act
await _customerCoordinatesService.SaveGeoCoordinate(1, 2);
//Assert
- Assert.AreEqual(1, _workContextMock.Object.CurrentCustomer.Coordinates.X);
- Assert.AreEqual(2, _workContextMock.Object.CurrentCustomer.Coordinates.Y);
+ Assert.AreEqual(1, _workContextMock.Object.WorkContext.CurrentCustomer.Coordinates.X);
+ Assert.AreEqual(2, _workContextMock.Object.WorkContext.CurrentCustomer.Coordinates.Y);
_mediatorMock.Verify(c => c.Publish(It.IsAny<CustomerCoordinatesEvent>(), default), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Services/MessageProviderServiceTest.cs b/src/Tests/Grand.Business.Messages.Tests/Services/MessageProviderServiceTest.cs
index 986df3619..e264c666d 100644
--- a/src/Tests/Grand.Business.Messages.Tests/Services/MessageProviderServiceTest.cs
+++ b/src/Tests/Grand.Business.Messages.Tests/Services/MessageProviderServiceTest.cs
@@ -32,7 +32,7 @@ public class MessageProviderServiceTest
private Mock<IMessageTokenProvider> _messageTokenProviderMock;
private Product _product;
private Mock<IQueuedEmailService> _queuedEmailServiceMock;
- private Mock<IStoreHelper> _storeHelperServiceMock;
+ private Mock<IWorkContextAccessor> _workContextAccessorMock;
private Mock<IStoreService> _storeServiceMock;
[TestInitialize]
@@ -62,8 +62,8 @@ public class MessageProviderServiceTest
.Returns(Task.FromResult(new Store { Url = "https://localhost:44350/" }));
_storeServiceMock.Setup(x => x.GetAllStores()).Returns(Task.FromResult(new List<Store>() as IList<Store>));
- _storeHelperServiceMock = new Mock<IStoreHelper>();
-
+ _workContextAccessorMock = new Mock<IWorkContextAccessor>();
+ _workContextAccessorMock.Setup(x => x.WorkContext.CurrentHost).Returns(new DomainHost { Url = "https://localhost:44350/" });
_mediatorMock = new Mock<IMediator>();
_mediatorMock.Setup(x => x.Send(It.IsAny<GetCustomerByIdQuery>(), default))
.Returns(Task.FromResult(new Customer { Email = "[email protected]" }));
@@ -72,12 +72,12 @@ public class MessageProviderServiceTest
_commonSetting = new Mock<CommonSettings>();
_messageService = new MessageProviderService(
+ _workContextAccessorMock.Object,
_messageTemplateServiceMock.Object,
_queuedEmailServiceMock.Object,
_languageServiceMock.Object,
_emailAccountServiceMock.Object,
_storeServiceMock.Object,
- _storeHelperServiceMock.Object,
_groupService.Object,
_mediatorMock.Object,
_emailAccountSettingsMock.Object,
diff --git a/src/Tests/Grand.Web.Common.Tests/AuthorizeMenuAttributeTests.cs b/src/Tests/Grand.Web.Common.Tests/AuthorizeMenuAttributeTests.cs
index 90dcd2300..531588cfd 100644
--- a/src/Tests/Grand.Web.Common.Tests/AuthorizeMenuAttributeTests.cs
+++ b/src/Tests/Grand.Web.Common.Tests/AuthorizeMenuAttributeTests.cs
@@ -24,7 +24,7 @@ public class AuthorizeMenuAttributeTests
private Mock<IAdminSiteMapService> _mockAdminSiteMapService;
private AuthorizationFilterContext _mockFilterContext;
private Mock<IPermissionService> _mockPermissionService;
- private Mock<IWorkContext> _mockWorkContext;
+ private Mock<IWorkContextAccessor> _mockWorkContext;
private SecurityConfig _securityConfig;
[TestInitialize]
@@ -35,7 +35,9 @@ public class AuthorizeMenuAttributeTests
var settings = DataSettingsManager.Instance.LoadSettings();
_mockPermissionService = new Mock<IPermissionService>();
_mockAdminSiteMapService = new Mock<IAdminSiteMapService>();
- _mockWorkContext = new Mock<IWorkContext>();
+ _mockWorkContext = new Mock<IWorkContextAccessor>();
+ _mockWorkContext.Setup(s => s.WorkContext.CurrentCustomer).Returns(new Customer());
+
_securityConfig = new SecurityConfig();
var filters = new List<IFilterMetadata> {
new AuthorizeMenuAttribute()
@@ -127,6 +129,7 @@ public class AuthorizeMenuAttributeTests
};
_mockAdminSiteMapService.Setup(s => s.GetSiteMap()).ReturnsAsync(new List<AdminSiteMap> { menuSiteMap });
_mockPermissionService.Setup(s => s.Authorize(It.IsAny<string>(), It.IsAny<Customer>())).ReturnsAsync(false);
+
_securityConfig.AuthorizeAdminMenu = true;
var attribute = new AuthorizeMenuAttribute();
var filter = new AuthorizeMenuAttribute.AuthorizeMenuFilter(
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Home/Index.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Home/Index.cshtml
index adc3b002b..ca79c0e23 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Home/Index.cshtml
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Home/Index.cshtml
@@ -10,18 +10,18 @@
@inject ICustomerService customerService
@inject IOrderReportService orderReportService
@inject IPriceFormatter priceFormatter
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@inject ICurrencyService currencyService
@inject IGroupService groupService
@{
//page title
ViewBag.Title = Loc["Admin.Dashboard"];
- var isAdminAccess = await groupService.IsAdmin(workContext.CurrentCustomer);
+ var isAdminAccess = await groupService.IsAdmin(workContextAccessor.WorkContext.CurrentCustomer);
var canAccessReports = await permissionService.Authorize(StandardPermission.ManageReports);
var canManageOrders = await permissionService.Authorize(StandardPermission.ManageOrders);
- var customersOnline = (await customerService.GetOnlineCustomers(DateTime.UtcNow.AddMinutes(-customerSettings.OnlineCustomerMinutes), null, workContext.CurrentCustomer.StaffStoreId, workContext.CurrentCustomer.SeId, 1, 1)).TotalCount;
- var customersShoppingCart = await customerService.GetCountOnlineShoppingCart(DateTime.UtcNow.AddMinutes(-customerSettings.OnlineShoppingCartMinutes), workContext.CurrentCustomer.StaffStoreId, workContext.CurrentCustomer.SeId);
- var ordersToday = await orderReportService.GetOrderPeriodReport(0, workContext.CurrentCustomer.StaffStoreId, workContext.CurrentCustomer.SeId);
+ var customersOnline = (await customerService.GetOnlineCustomers(DateTime.UtcNow.AddMinutes(-customerSettings.OnlineCustomerMinutes), null, workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId, workContextAccessor.WorkContext.CurrentCustomer.SeId, 1, 1)).TotalCount;
+ var customersShoppingCart = await customerService.GetCountOnlineShoppingCart(DateTime.UtcNow.AddMinutes(-customerSettings.OnlineShoppingCartMinutes), workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId, workContextAccessor.WorkContext.CurrentCustomer.SeId);
+ var ordersToday = await orderReportService.GetOrderPeriodReport(0, workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId, workContextAccessor.WorkContext.CurrentCustomer.SeId);
var ordersAmount = priceFormatter.FormatPrice(ordersToday.Amount, await currencyService.GetPrimaryStoreCurrency());
}
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/Partials/HeadAdmin.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/Partials/HeadAdmin.cshtml
index 2b086b4e9..7d8942c87 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/Partials/HeadAdmin.cshtml
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/Partials/HeadAdmin.cshtml
@@ -1,12 +1,12 @@
@using Grand.Domain.Localization
@using Constants = Grand.SharedUIResources.Constants
@inject LanguageSettings languageSettings
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
<script>
const wwwrootpath = '@(Constants.WwwRoot)';
</script>
@{
- var supportRtl = workContext.WorkingLanguage.Rtl &&
+ var supportRtl = workContextAccessor.WorkContext.WorkingLanguage.Rtl &&
!languageSettings.IgnoreRtlPropertyForAdminArea;
var kendoVersion = "2021.3.914";
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/_AdminLayout.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/_AdminLayout.cshtml
index 2c0e02d1f..7f0c322a7 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/_AdminLayout.cshtml
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Shared/_AdminLayout.cshtml
@@ -4,16 +4,16 @@
@using Grand.Domain.Permissions
@using Grand.Domain.Customers
@using Grand.Domain.Localization
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@inject IPermissionService permissionService
@inject CustomerSettings customerSettings
@inject LanguageSettings languageSettings
@inject IGroupService groupService
@{
- var currentCustomer = workContext.CurrentCustomer;
+ var currentCustomer = workContextAccessor.WorkContext.CurrentCustomer;
var usernamesEnabled = customerSettings.UsernamesEnabled;
var currentVersion = GrandVersion.FullVersion;
- var supportRtl = workContext.WorkingLanguage.Rtl &&
+ var supportRtl = workContextAccessor.WorkContext.WorkingLanguage.Rtl &&
!languageSettings.IgnoreRtlPropertyForAdminArea;
//page title
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/VendorReview/Edit.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/VendorReview/Edit.cshtml
index 93deb5cda..cbd713b9e 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/VendorReview/Edit.cshtml
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/VendorReview/Edit.cshtml
@@ -1,5 +1,5 @@
@model VendorReviewModel
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@{
//page title
ViewBag.Title = Loc["Admin.VendorReviews.EditVendorReviewDetails"];
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/VendorReview/Partials/CreateOrUpdate.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/VendorReview/Partials/CreateOrUpdate.cshtml
index 9f9ff08a3..41f49b666 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/VendorReview/Partials/CreateOrUpdate.cshtml
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/VendorReview/Partials/CreateOrUpdate.cshtml
@@ -1,5 +1,5 @@
@model VendorReviewModel
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@Html.ValidationSummary(false)
<input asp-for="Id" type="hidden"/>
<div class="form-horizontal">
diff --git a/src/Web/Grand.Web.Admin/Components/AdminLanguageSelector.cs b/src/Web/Grand.Web.Admin/Components/AdminLanguageSelector.cs
index d0fd1969b..a4071cda6 100644
--- a/src/Web/Grand.Web.Admin/Components/AdminLanguageSelector.cs
+++ b/src/Web/Grand.Web.Admin/Components/AdminLanguageSelector.cs
@@ -10,24 +10,24 @@ namespace Grand.Web.Admin.Components;
public class AdminLanguageSelectorViewComponent : BaseAdminViewComponent
{
private readonly ILanguageService _languageService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public AdminLanguageSelectorViewComponent(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ILanguageService languageService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_languageService = languageService;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var model = new LanguageSelectorModel {
- CurrentLanguage = _workContext.WorkingLanguage.ToModel(),
+ CurrentLanguage = _workContextAccessor.WorkContext.WorkingLanguage.ToModel(),
AvailableLanguages = (await _languageService
.GetAllLanguages(
true,
- _workContext.CurrentStore.Id))
+ _workContextAccessor.WorkContext.CurrentStore.Id))
.Select(x => x.ToModel())
.ToList()
};
diff --git a/src/Web/Grand.Web.Admin/Components/AdminWidget.cs b/src/Web/Grand.Web.Admin/Components/AdminWidget.cs
index 03f039bb1..908998531 100644
--- a/src/Web/Grand.Web.Admin/Components/AdminWidget.cs
+++ b/src/Web/Grand.Web.Admin/Components/AdminWidget.cs
@@ -10,10 +10,10 @@ public class AdminWidgetViewComponent : BaseAdminViewComponent
{
#region Constructors
- public AdminWidgetViewComponent(IWidgetService widgetService, IWorkContext workContext)
+ public AdminWidgetViewComponent(IWidgetService widgetService, IWorkContextAccessor workContextAccessor)
{
_widgetService = widgetService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
#endregion
@@ -24,8 +24,8 @@ public class AdminWidgetViewComponent : BaseAdminViewComponent
{
var model = new List<AdminWidgetModel>();
- var widgets = await _widgetService.LoadActiveWidgetsByWidgetZone(widgetZone, _workContext.CurrentStore.Id,
- _workContext.CurrentCustomer);
+ var widgets = await _widgetService.LoadActiveWidgetsByWidgetZone(widgetZone, _workContextAccessor.WorkContext.CurrentStore.Id,
+ _workContextAccessor.WorkContext.CurrentCustomer);
foreach (var item in widgets)
{
var viewComponentName = await item.GetPublicViewComponentName(widgetZone);
@@ -50,7 +50,7 @@ public class AdminWidgetViewComponent : BaseAdminViewComponent
#region Fields
private readonly IWidgetService _widgetService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
#endregion
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Admin/Components/LatestOrder.cs b/src/Web/Grand.Web.Admin/Components/LatestOrder.cs
index 95186754d..33dfca307 100644
--- a/src/Web/Grand.Web.Admin/Components/LatestOrder.cs
+++ b/src/Web/Grand.Web.Admin/Components/LatestOrder.cs
@@ -9,12 +9,12 @@ namespace Grand.Web.Admin.Components;
public class LatestOrderViewComponent : BaseAdminViewComponent
{
private readonly IPermissionService _permissionService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public LatestOrderViewComponent(IPermissionService permissionService, IWorkContext workContext)
+ public LatestOrderViewComponent(IPermissionService permissionService, IWorkContextAccessor workContextAccessor)
{
_permissionService = permissionService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<IViewComponentResult> InvokeAsync()
diff --git a/src/Web/Grand.Web.Admin/Components/StoreScope.cs b/src/Web/Grand.Web.Admin/Components/StoreScope.cs
index 80d0a2e00..78122f52a 100644
--- a/src/Web/Grand.Web.Admin/Components/StoreScope.cs
+++ b/src/Web/Grand.Web.Admin/Components/StoreScope.cs
@@ -15,10 +15,10 @@ public class StoreScopeViewComponent : BaseAdminViewComponent
{
#region Constructors
- public StoreScopeViewComponent(IStoreService storeService, IWorkContext workContext, IGroupService groupService)
+ public StoreScopeViewComponent(IStoreService storeService, IWorkContextAccessor workContextAccessor, IGroupService groupService)
{
_storeService = storeService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
}
@@ -32,8 +32,8 @@ public class StoreScopeViewComponent : BaseAdminViewComponent
if (allStores.Count < 2)
return Content("");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- allStores = allStores.Where(x => x.Id == _workContext.CurrentCustomer.StaffStoreId).ToList();
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ allStores = allStores.Where(x => x.Id == _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId).ToList();
var model = new StoreScopeModel();
foreach (var s in allStores)
@@ -56,7 +56,7 @@ public class StoreScopeViewComponent : BaseAdminViewComponent
return stores.FirstOrDefault()!.Id;
var storeId =
- _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames
+ _workContextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames
.AdminAreaStoreScopeConfiguration);
var store = await _storeService.GetStoreById(storeId);
@@ -68,7 +68,7 @@ public class StoreScopeViewComponent : BaseAdminViewComponent
#region Fields
private readonly IStoreService _storeService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
#endregion
diff --git a/src/Web/Grand.Web.Admin/Controllers/BaseAdminController.cs b/src/Web/Grand.Web.Admin/Controllers/BaseAdminController.cs
index 4152832a4..adb8eba5c 100644
--- a/src/Web/Grand.Web.Admin/Controllers/BaseAdminController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/BaseAdminController.cs
@@ -55,7 +55,7 @@ public abstract class BaseAdminController : BaseController
protected async Task<string> GetActiveStore()
{
var storeService = HttpContext.RequestServices.GetRequiredService<IStoreService>();
- var workContext = HttpContext.RequestServices.GetRequiredService<IWorkContext>();
+ var workContext = HttpContext.RequestServices.GetRequiredService<IWorkContextAccessor>().WorkContext;
var groupService = HttpContext.RequestServices.GetRequiredService<IGroupService>();
var stores = await storeService.GetAllStores();
diff --git a/src/Web/Grand.Web.Admin/Controllers/BlogController.cs b/src/Web/Grand.Web.Admin/Controllers/BlogController.cs
index 6af570c6e..51ac36ffa 100644
--- a/src/Web/Grand.Web.Admin/Controllers/BlogController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/BlogController.cs
@@ -30,7 +30,7 @@ public class BlogController : BaseAdminController
ILanguageService languageService,
ITranslationService translationService,
IStoreService storeService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
IDateTimeService dateTimeService,
IPictureViewModelService pictureViewModelService,
@@ -41,7 +41,7 @@ public class BlogController : BaseAdminController
_languageService = languageService;
_translationService = translationService;
_storeService = storeService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_dateTimeService = dateTimeService;
_pictureViewModelService = pictureViewModelService;
@@ -57,7 +57,7 @@ public class BlogController : BaseAdminController
private readonly ILanguageService _languageService;
private readonly ITranslationService _translationService;
private readonly IStoreService _storeService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
private readonly IDateTimeService _dateTimeService;
private readonly IPictureViewModelService _pictureViewModelService;
@@ -110,8 +110,8 @@ public class BlogController : BaseAdminController
{
if (ModelState.IsValid)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
var blogPost = await _blogViewModelService.InsertBlogPostModel(model);
Success(_translationService.GetResource("Admin.Content.Blog.BlogPosts.Added"));
return continueEditing ? RedirectToAction("Edit", new { id = blogPost.Id }) : RedirectToAction("List");
@@ -131,17 +131,17 @@ public class BlogController : BaseAdminController
//No blog post found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
{
if (!blogPost.LimitedToStores || (blogPost.LimitedToStores &&
- blogPost.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ blogPost.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
blogPost.Stores.Count > 1))
{
Warning(_translationService.GetResource("Admin.Content.Blog.BlogPosts.Permissions"));
}
else
{
- if (!blogPost.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (!blogPost.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("List");
}
}
@@ -172,14 +172,14 @@ public class BlogController : BaseAdminController
//No blog post found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!blogPost.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!blogPost.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = blogPost.Id });
if (ModelState.IsValid)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
blogPost = await _blogViewModelService.UpdateBlogPostModel(model, blogPost);
@@ -221,8 +221,8 @@ public class BlogController : BaseAdminController
//No blog post found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!blogPost.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!blogPost.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = blogPost.Id });
if (ModelState.IsValid)
@@ -294,7 +294,7 @@ public class BlogController : BaseAdminController
[HttpPost]
public async Task<IActionResult> CategoryList(DataSourceRequest command)
{
- var categories = await _blogService.GetAllBlogCategories(_workContext.CurrentCustomer.StaffStoreId);
+ var categories = await _blogService.GetAllBlogCategories(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
var gridModel = new DataSourceResult {
Data = categories,
Total = categories.Count
@@ -320,8 +320,8 @@ public class BlogController : BaseAdminController
{
if (ModelState.IsValid)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
var blogCategory = model.ToEntity();
blogCategory.SeName = SeoExtensions.GetSeName(
@@ -351,18 +351,18 @@ public class BlogController : BaseAdminController
//No blog post found with the specified id
return RedirectToAction("CategoryList");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
{
if (!blogCategory.LimitedToStores || (blogCategory.LimitedToStores &&
blogCategory.Stores.Contains(
- _workContext.CurrentCustomer.StaffStoreId) &&
+ _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
blogCategory.Stores.Count > 1))
{
Warning(_translationService.GetResource("Admin.Content.Blog.BlogCategory.Permissions"));
}
else
{
- if (!blogCategory.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (!blogCategory.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("List");
}
}
@@ -387,14 +387,14 @@ public class BlogController : BaseAdminController
//No blog post found with the specified id
return RedirectToAction("CategoryList");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!blogCategory.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!blogCategory.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("CategoryEdit", new { id = blogCategory.Id });
if (ModelState.IsValid)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
blogCategory = model.ToEntity(blogCategory);
blogCategory.SeName = SeoExtensions.GetSeName(
@@ -435,8 +435,8 @@ public class BlogController : BaseAdminController
//No blog post found with the specified id
return RedirectToAction("CategoryList");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!blogcategory.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!blogcategory.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("CategoryEdit", new { id = blogcategory.Id });
if (ModelState.IsValid)
@@ -487,8 +487,8 @@ public class BlogController : BaseAdminController
if (blogCategory == null)
return ErrorForKendoGridJson("blogCategory no exists");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!blogCategory.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!blogCategory.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return ErrorForKendoGridJson("blogCategory no permission");
if (ModelState.IsValid)
@@ -511,7 +511,7 @@ public class BlogController : BaseAdminController
{
var model = new AddBlogPostCategoryModel();
//stores
- var storeId = _workContext.CurrentCustomer.StaffStoreId;
+ var storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
model.AvailableStores.Add(new SelectListItem
{ Text = _translationService.GetResource("Admin.Common.All"), Value = " " });
@@ -528,8 +528,8 @@ public class BlogController : BaseAdminController
{
var gridModel = new DataSourceResult();
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.SearchStoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.SearchStoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var posts = await _blogService.GetAllBlogPosts(model.SearchStoreId, blogPostName: model.SearchBlogTitle,
pageIndex: command.Page - 1, pageSize: command.PageSize);
@@ -593,8 +593,8 @@ public class BlogController : BaseAdminController
throw new ArgumentException("No comment found with the specified id");
var blogPost = await _blogService.GetBlogPostById(comment.BlogPostId);
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!blogPost.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!blogPost.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return ErrorForKendoGridJson("blogPost no permission");
if (ModelState.IsValid)
diff --git a/src/Web/Grand.Web.Admin/Controllers/BrandController.cs b/src/Web/Grand.Web.Admin/Controllers/BrandController.cs
index 564c03cad..0a3272add 100644
--- a/src/Web/Grand.Web.Admin/Controllers/BrandController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/BrandController.cs
@@ -30,7 +30,7 @@ public class BrandController : BaseAdminController
public BrandController(
IBrandViewModelService brandViewModelService,
IBrandService brandService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IStoreService storeService,
ILanguageService languageService,
ITranslationService translationService,
@@ -39,7 +39,7 @@ public class BrandController : BaseAdminController
{
_brandViewModelService = brandViewModelService;
_brandService = brandService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_storeService = storeService;
_languageService = languageService;
_translationService = translationService;
@@ -54,8 +54,8 @@ public class BrandController : BaseAdminController
protected async Task<(bool allow, string message)> CheckAccessToBrand(Brand brand)
{
if (brand == null) return (false, "Brand not exists");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!(!brand.LimitedToStores || (brand.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!(!brand.LimitedToStores || (brand.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
brand.LimitedToStores)))
return (false, "This is not your collection");
return (true, null);
@@ -67,7 +67,7 @@ public class BrandController : BaseAdminController
private readonly IBrandViewModelService _brandViewModelService;
private readonly IBrandService _brandService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IStoreService _storeService;
private readonly ILanguageService _languageService;
private readonly ITranslationService _translationService;
@@ -85,7 +85,7 @@ public class BrandController : BaseAdminController
public async Task<IActionResult> List()
{
- var storeId = _workContext.CurrentCustomer.StaffStoreId;
+ var storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var model = new BrandListModel();
model.AvailableStores.Add(new SelectListItem
{ Text = _translationService.GetResource("Admin.Common.All"), Value = "" });
@@ -100,8 +100,8 @@ public class BrandController : BaseAdminController
[HttpPost]
public async Task<IActionResult> List(DataSourceRequest command, BrandListModel model)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.SearchStoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.SearchStoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var brands = await _brandService.GetAllBrands(model.SearchBrandName,
model.SearchStoreId, command.Page - 1, command.PageSize, true);
var gridModel = new DataSourceResult {
@@ -144,8 +144,8 @@ public class BrandController : BaseAdminController
{
if (ModelState.IsValid)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
var collection = await _brandViewModelService.InsertBrandModel(model);
Success(_translationService.GetResource("Admin.Catalog.Brands.Added"));
@@ -171,17 +171,17 @@ public class BrandController : BaseAdminController
//No collection found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
{
if (!brand.LimitedToStores || (brand.LimitedToStores &&
- brand.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ brand.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
brand.Stores.Count > 1))
{
Warning(_translationService.GetResource("Admin.Catalog.Brands.Permissions"));
}
else
{
- if (!brand.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (!brand.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("List");
}
}
@@ -218,13 +218,13 @@ public class BrandController : BaseAdminController
//No collection found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!brand.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!brand.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = brand.Id });
if (ModelState.IsValid)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
brand = await _brandViewModelService.UpdateBrandModel(brand, model);
Success(_translationService.GetResource("Admin.Catalog.Brands.Updated"));
@@ -260,8 +260,8 @@ public class BrandController : BaseAdminController
//No collection found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!brand.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!brand.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = brand.Id });
if (ModelState.IsValid)
@@ -338,7 +338,7 @@ public class BrandController : BaseAdminController
try
{
var bytes = await exportManager.Export(await _brandService.GetAllBrands(showHidden: true,
- storeId: _workContext.CurrentCustomer.StaffStoreId));
+ storeId: _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId));
return File(bytes, "text/xls", "brands.xlsx");
}
catch (Exception exc)
diff --git a/src/Web/Grand.Web.Admin/Controllers/CampaignController.cs b/src/Web/Grand.Web.Admin/Controllers/CampaignController.cs
index 429952d19..3bd80afb8 100644
--- a/src/Web/Grand.Web.Admin/Controllers/CampaignController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/CampaignController.cs
@@ -27,13 +27,13 @@ public class CampaignController : BaseAdminController
private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService;
private readonly IStoreService _storeService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public CampaignController(ICampaignService campaignService, ICampaignViewModelService campaignViewModelService,
IEmailAccountService emailAccountService,
INewsLetterSubscriptionService newsLetterSubscriptionService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IStoreService storeService,
EmailAccountSettings emailAccountSettings)
{
@@ -43,7 +43,7 @@ public class CampaignController : BaseAdminController
_emailAccountSettings = emailAccountSettings;
_newsLetterSubscriptionService = newsLetterSubscriptionService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_storeService = storeService;
}
@@ -206,7 +206,7 @@ public class CampaignController : BaseAdminController
var subscription =
await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(model.TestEmail,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
if (subscription != null)
{
//there's a subscription. use it
diff --git a/src/Web/Grand.Web.Admin/Controllers/CategoryController.cs b/src/Web/Grand.Web.Admin/Controllers/CategoryController.cs
index 51e4ef020..337673ea7 100644
--- a/src/Web/Grand.Web.Admin/Controllers/CategoryController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/CategoryController.cs
@@ -30,7 +30,7 @@ public class CategoryController : BaseAdminController
ICategoryViewModelService categoryViewModelService,
ILanguageService languageService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
IPictureViewModelService pictureViewModelService)
{
@@ -38,7 +38,7 @@ public class CategoryController : BaseAdminController
_categoryViewModelService = categoryViewModelService;
_languageService = languageService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_pictureViewModelService = pictureViewModelService;
}
@@ -50,8 +50,8 @@ public class CategoryController : BaseAdminController
protected async Task<(bool allow, string message)> CheckAccessToCategory(Category category)
{
if (category == null) return (false, "Category not exists");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!(!category.LimitedToStores || (category.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!(!category.LimitedToStores || (category.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
category.LimitedToStores)))
return (false, "This is not your category");
return (true, null);
@@ -65,7 +65,7 @@ public class CategoryController : BaseAdminController
private readonly ICategoryViewModelService _categoryViewModelService;
private readonly ILanguageService _languageService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
private readonly IPictureViewModelService _pictureViewModelService;
@@ -80,7 +80,7 @@ public class CategoryController : BaseAdminController
public async Task<IActionResult> List()
{
- var model = await _categoryViewModelService.PrepareCategoryListModel(_workContext.CurrentCustomer.StaffStoreId);
+ var model = await _categoryViewModelService.PrepareCategoryListModel(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
return View(model);
}
@@ -88,8 +88,8 @@ public class CategoryController : BaseAdminController
[HttpPost]
public async Task<IActionResult> List(DataSourceRequest command, CategoryListModel model)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.SearchStoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.SearchStoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var categories =
await _categoryViewModelService.PrepareCategoryListModel(model, command.Page, command.PageSize);
@@ -107,7 +107,7 @@ public class CategoryController : BaseAdminController
[PermissionAuthorizeAction(PermissionActionName.Create)]
public async Task<IActionResult> Create()
{
- var model = await _categoryViewModelService.PrepareCategoryModel(_workContext.CurrentCustomer.StaffStoreId);
+ var model = await _categoryViewModelService.PrepareCategoryModel(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
//locales
await AddLocales(_languageService, model.Locales);
@@ -121,8 +121,8 @@ public class CategoryController : BaseAdminController
{
if (ModelState.IsValid)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
var category = await _categoryViewModelService.InsertCategoryModel(model);
Success(_translationService.GetResource("Admin.Catalog.Categories.Added"));
@@ -131,7 +131,7 @@ public class CategoryController : BaseAdminController
//If we got this far, something failed, redisplay form
model = await _categoryViewModelService.PrepareCategoryModel(model, null,
- _workContext.CurrentCustomer.StaffStoreId);
+ _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
return View(model);
}
@@ -144,17 +144,17 @@ public class CategoryController : BaseAdminController
//No category found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
{
if (!category.LimitedToStores || (category.LimitedToStores &&
- category.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ category.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
category.Stores.Count > 1))
{
Warning(_translationService.GetResource("Admin.Catalog.Categories.Permissions"));
}
else
{
- if (!category.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (!category.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("List");
}
}
@@ -173,7 +173,7 @@ public class CategoryController : BaseAdminController
locale.Flag = category.GetTranslation(x => x.Flag, languageId, false);
});
model = await _categoryViewModelService.PrepareCategoryModel(model, category,
- _workContext.CurrentCustomer.StaffStoreId);
+ _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
return View(model);
}
@@ -188,14 +188,14 @@ public class CategoryController : BaseAdminController
//No category found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!category.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!category.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = category.Id });
if (ModelState.IsValid)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
category = await _categoryViewModelService.UpdateCategoryModel(category, model);
@@ -213,7 +213,7 @@ public class CategoryController : BaseAdminController
//If we got this far, something failed, redisplay form
model = await _categoryViewModelService.PrepareCategoryModel(model, category,
- _workContext.CurrentCustomer.StaffStoreId);
+ _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
return View(model);
}
@@ -227,8 +227,8 @@ public class CategoryController : BaseAdminController
//No category found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!category.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!category.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = category.Id });
if (ModelState.IsValid)
@@ -298,7 +298,7 @@ public class CategoryController : BaseAdminController
try
{
var bytes = await exportManager.Export(await _categoryService.GetAllCategories(showHidden: true,
- storeId: _workContext.CurrentCustomer.StaffStoreId));
+ storeId: _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId));
return File(bytes, "text/xls", "categories.xlsx");
}
catch (Exception exc)
@@ -385,7 +385,7 @@ public class CategoryController : BaseAdminController
[PermissionAuthorizeAction(PermissionActionName.Edit)]
public async Task<IActionResult> ProductAddPopup(string categoryId)
{
- var model = await _categoryViewModelService.PrepareAddCategoryProductModel(_workContext.CurrentCustomer
+ var model = await _categoryViewModelService.PrepareAddCategoryProductModel(_workContextAccessor.WorkContext.CurrentCustomer
.StaffStoreId);
model.CategoryId = categoryId;
return View(model);
@@ -397,8 +397,8 @@ public class CategoryController : BaseAdminController
CategoryModel.AddCategoryProductModel model)
{
var gridModel = new DataSourceResult();
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.SearchStoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.SearchStoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var products = await _categoryViewModelService.PrepareProductModel(model, command.Page, command.PageSize);
gridModel.Data = products.products.ToList();
gridModel.Total = products.totalCount;
diff --git a/src/Web/Grand.Web.Admin/Controllers/CollectionController.cs b/src/Web/Grand.Web.Admin/Controllers/CollectionController.cs
index 97798944a..72962d428 100644
--- a/src/Web/Grand.Web.Admin/Controllers/CollectionController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/CollectionController.cs
@@ -30,7 +30,7 @@ public class CollectionController : BaseAdminController
public CollectionController(
ICollectionViewModelService collectionViewModelService,
ICollectionService collectionService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IStoreService storeService,
ILanguageService languageService,
ITranslationService translationService,
@@ -39,7 +39,7 @@ public class CollectionController : BaseAdminController
{
_collectionViewModelService = collectionViewModelService;
_collectionService = collectionService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_storeService = storeService;
_languageService = languageService;
_translationService = translationService;
@@ -54,9 +54,9 @@ public class CollectionController : BaseAdminController
protected async Task<(bool allow, string message)> CheckAccessToCollection(Collection collection)
{
if (collection == null) return (false, "Collection not exists");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
if (!(!collection.LimitedToStores ||
- (collection.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ (collection.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
collection.LimitedToStores)))
return (false, "This is not your collection");
return (true, null);
@@ -68,7 +68,7 @@ public class CollectionController : BaseAdminController
private readonly ICollectionViewModelService _collectionViewModelService;
private readonly ICollectionService _collectionService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IStoreService _storeService;
private readonly ILanguageService _languageService;
private readonly ITranslationService _translationService;
@@ -86,7 +86,7 @@ public class CollectionController : BaseAdminController
public async Task<IActionResult> List()
{
- var storeId = _workContext.CurrentCustomer.StaffStoreId;
+ var storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var model = new CollectionListModel();
model.AvailableStores.Add(new SelectListItem
{ Text = _translationService.GetResource("Admin.Common.All"), Value = "" });
@@ -101,8 +101,8 @@ public class CollectionController : BaseAdminController
[HttpPost]
public async Task<IActionResult> List(DataSourceRequest command, CollectionListModel model)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.SearchStoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.SearchStoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var collections = await _collectionService.GetAllCollections(model.SearchCollectionName,
model.SearchStoreId, command.Page - 1, command.PageSize, true);
var gridModel = new DataSourceResult {
@@ -145,8 +145,8 @@ public class CollectionController : BaseAdminController
{
if (ModelState.IsValid)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
var collection = await _collectionViewModelService.InsertCollectionModel(model);
Success(_translationService.GetResource("Admin.Catalog.Collections.Added"));
@@ -172,17 +172,17 @@ public class CollectionController : BaseAdminController
//No collection found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
{
if (!collection.LimitedToStores || (collection.LimitedToStores &&
- collection.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ collection.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
collection.Stores.Count > 1))
{
Warning(_translationService.GetResource("Admin.Catalog.Collections.Permissions"));
}
else
{
- if (!collection.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (!collection.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("List");
}
}
@@ -219,13 +219,13 @@ public class CollectionController : BaseAdminController
//No collection found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!collection.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!collection.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = collection.Id });
if (ModelState.IsValid)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
collection = await _collectionViewModelService.UpdateCollectionModel(collection, model);
Success(_translationService.GetResource("Admin.Catalog.Collections.Updated"));
@@ -261,8 +261,8 @@ public class CollectionController : BaseAdminController
//No collection found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!collection.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!collection.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = collection.Id });
if (ModelState.IsValid)
@@ -339,7 +339,7 @@ public class CollectionController : BaseAdminController
try
{
var bytes = await exportManager.Export(await _collectionService.GetAllCollections(showHidden: true,
- storeId: _workContext.CurrentCustomer.StaffStoreId));
+ storeId: _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId));
return File(bytes, "text/xls", "collections.xlsx");
}
catch (Exception exc)
@@ -390,7 +390,7 @@ public class CollectionController : BaseAdminController
return ErrorForKendoGridJson(permission.message);
var (collectionProductModels, totalCount) =
- await _collectionViewModelService.PrepareCollectionProductModel(collectionId, _workContext.CurrentStore.Id,
+ await _collectionViewModelService.PrepareCollectionProductModel(collectionId, _workContextAccessor.WorkContext.CurrentStore.Id,
command.Page, command.PageSize);
var gridModel = new DataSourceResult {
@@ -429,7 +429,7 @@ public class CollectionController : BaseAdminController
[PermissionAuthorizeAction(PermissionActionName.Edit)]
public async Task<IActionResult> ProductAddPopup(string collectionId)
{
- var model = await _collectionViewModelService.PrepareAddCollectionProductModel(_workContext.CurrentCustomer
+ var model = await _collectionViewModelService.PrepareAddCollectionProductModel(_workContextAccessor.WorkContext.CurrentCustomer
.StaffStoreId);
model.CollectionId = collectionId;
return View(model);
@@ -440,8 +440,8 @@ public class CollectionController : BaseAdminController
public async Task<IActionResult> ProductAddPopupList(DataSourceRequest command,
CollectionModel.AddCollectionProductModel model)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.SearchStoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.SearchStoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var products = await _collectionViewModelService.PrepareProductModel(model, command.Page, command.PageSize);
var gridModel = new DataSourceResult {
Data = products.products.ToList(),
diff --git a/src/Web/Grand.Web.Admin/Controllers/CourseController.cs b/src/Web/Grand.Web.Admin/Controllers/CourseController.cs
index 5e9f27b54..e0640ae01 100644
--- a/src/Web/Grand.Web.Admin/Controllers/CourseController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/CourseController.cs
@@ -30,7 +30,7 @@ public class CourseController : BaseAdminController
private readonly ILanguageService _languageService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public CourseController(
ITranslationService translationService,
@@ -39,7 +39,7 @@ public class CourseController : BaseAdminController
ICourseSubjectService courseSubjectService,
ICourseLessonService courseLessonService,
ICourseViewModelService courseViewModelService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ILanguageService languageService,
IGroupService groupService)
{
@@ -49,7 +49,7 @@ public class CourseController : BaseAdminController
_courseSubjectService = courseSubjectService;
_courseLessonService = courseLessonService;
_courseViewModelService = courseViewModelService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_languageService = languageService;
_groupService = groupService;
}
@@ -154,8 +154,8 @@ public class CourseController : BaseAdminController
{
if (ModelState.IsValid)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
var course = await _courseViewModelService.InsertCourseModel(model);
Success(_translationService.GetResource("Admin.Courses.Course.Added"));
@@ -176,17 +176,17 @@ public class CourseController : BaseAdminController
//No course found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
{
if (!course.LimitedToStores || (course.LimitedToStores &&
- course.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ course.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
course.Stores.Count > 1))
{
Warning(_translationService.GetResource("Admin.Courses.Course.Permissions"));
}
else
{
- if (!course.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (!course.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("List");
}
}
@@ -219,14 +219,14 @@ public class CourseController : BaseAdminController
//No course found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!course.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!course.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = course.Id });
if (ModelState.IsValid)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
course = await _courseViewModelService.UpdateCourseModel(course, model);
@@ -257,8 +257,8 @@ public class CourseController : BaseAdminController
//No course found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!course.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!course.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = course.Id });
if (ModelState.IsValid)
@@ -393,17 +393,17 @@ public class CourseController : BaseAdminController
//No course found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
{
if (!course.LimitedToStores || (course.LimitedToStores &&
- course.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ course.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
course.Stores.Count > 1))
{
Warning(_translationService.GetResource("Admin.Courses.Course.Permissions"));
}
else
{
- if (!course.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (!course.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("List");
}
}
@@ -423,17 +423,17 @@ public class CourseController : BaseAdminController
//No course found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
{
if (!course.LimitedToStores || (course.LimitedToStores &&
- course.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ course.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
course.Stores.Count > 1))
{
Warning(_translationService.GetResource("Admin.Courses.Course.Permissions"));
}
else
{
- if (!course.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (!course.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("List");
}
}
@@ -467,17 +467,17 @@ public class CourseController : BaseAdminController
//No course found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
{
if (!course.LimitedToStores || (course.LimitedToStores &&
- course.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ course.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
course.Stores.Count > 1))
{
Warning(_translationService.GetResource("Admin.Courses.Course.Permissions"));
}
else
{
- if (!course.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (!course.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("List");
}
}
@@ -502,8 +502,8 @@ public class CourseController : BaseAdminController
//No category found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!course.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!course.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = course.Id });
if (ModelState.IsValid)
{
@@ -540,8 +540,8 @@ public class CourseController : BaseAdminController
//No category found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!course.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!course.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = course.Id });
await _courseViewModelService.DeleteCourseLesson(lesson);
Success(_translationService.GetResource("Admin.Courses.Course.Lesson.Deleted"));
diff --git a/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs b/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs
index 3a2d47e3d..f092998a2 100644
--- a/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs
@@ -41,7 +41,7 @@ public class CustomerController : BaseAdminController
ICustomerViewModelService customerViewModelService,
ICustomerManagerService customerManagerService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
IExportManager<Customer> exportManager,
ICustomerAttributeParser customerAttributeParser,
@@ -59,7 +59,7 @@ public class CustomerController : BaseAdminController
_customerViewModelService = customerViewModelService;
_customerManagerService = customerManagerService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_exportManager = exportManager;
_customerAttributeParser = customerAttributeParser;
@@ -143,8 +143,8 @@ public class CustomerController : BaseAdminController
protected virtual async Task<bool> CheckSalesManager(Customer customer)
{
- return await _groupService.IsSalesManager(_workContext.CurrentCustomer)
- && _workContext.CurrentCustomer.SeId != customer.SeId;
+ return await _groupService.IsSalesManager(_workContextAccessor.WorkContext.CurrentCustomer)
+ && _workContextAccessor.WorkContext.CurrentCustomer.SeId != customer.SeId;
}
#region Message contact form
@@ -192,7 +192,7 @@ public class CustomerController : BaseAdminController
private readonly ICustomerViewModelService _customerViewModelService;
private readonly ICustomerManagerService _customerManagerService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IExportManager<Customer> _exportManager;
private readonly ICustomerAttributeParser _customerAttributeParser;
private readonly ICustomerAttributeService _customerAttributeService;
@@ -387,7 +387,7 @@ public class CustomerController : BaseAdminController
//No customer found with the specified id
return RedirectToAction("List");
- if (customer.Id == _workContext.CurrentCustomer.Id)
+ if (customer.Id == _workContextAccessor.WorkContext.CurrentCustomer.Id)
{
Error(_translationService.GetResource("Admin.Customers.Customers.NoSelfDelete"));
return RedirectToAction("List");
@@ -435,13 +435,13 @@ public class CustomerController : BaseAdminController
return RedirectToAction("Edit", customer.Id);
}
- if (!await _groupService.IsAdmin(_workContext.CurrentCustomer) && await _groupService.IsAdmin(customer))
+ if (!await _groupService.IsAdmin(_workContextAccessor.WorkContext.CurrentCustomer) && await _groupService.IsAdmin(customer))
{
Error("A non-admin user cannot impersonate as an administrator");
return RedirectToAction("Edit", customer.Id);
}
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.ImpersonatedCustomerId, customer.Id);
return RedirectToAction("Index", "Home", new { area = "" });
@@ -456,8 +456,8 @@ public class CustomerController : BaseAdminController
//No customer found with the specified id
return RedirectToAction("List");
- await _messageProviderService.SendCustomerWelcomeMessage(customer, _workContext.CurrentStore,
- _workContext.WorkingLanguage.Id);
+ await _messageProviderService.SendCustomerWelcomeMessage(customer, _workContextAccessor.WorkContext.CurrentStore,
+ _workContextAccessor.WorkContext.WorkingLanguage.Id);
Success(_translationService.GetResource("Admin.Customers.Customers.SendWelcomeMessage.Success"));
@@ -476,8 +476,8 @@ public class CustomerController : BaseAdminController
//email validation message
await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.AccountActivationToken,
Guid.NewGuid().ToString());
- await _messageProviderService.SendCustomerEmailValidationMessage(customer, _workContext.CurrentStore,
- _workContext.WorkingLanguage.Id);
+ await _messageProviderService.SendCustomerEmailValidationMessage(customer, _workContextAccessor.WorkContext.CurrentStore,
+ _workContextAccessor.WorkContext.WorkingLanguage.Id);
Success(_translationService.GetResource("Admin.Customers.Customers.ReSendActivationMessage.Success"));
@@ -696,8 +696,8 @@ public class CustomerController : BaseAdminController
var model = new OrderListModel {
CustomerId = customerId
};
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.StoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.StoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var (orderModels, totalCount) =
await orderViewModelService.PrepareOrderModel(model, command.Page, command.PageSize);
@@ -723,8 +723,8 @@ public class CustomerController : BaseAdminController
if (order == null)
throw new ArgumentException("No order found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- order.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return Json(new DataSourceResult {
Data = null,
Total = 0
@@ -968,7 +968,7 @@ public class CustomerController : BaseAdminController
public async Task<IActionResult> ExportExcelAll(CustomerListModel model)
{
var salesEmployeeId =
- await _groupService.IsSalesManager(_workContext.CurrentCustomer) ? _workContext.CurrentCustomer.SeId : "";
+ await _groupService.IsSalesManager(_workContextAccessor.WorkContext.CurrentCustomer) ? _workContextAccessor.WorkContext.CurrentCustomer.SeId : "";
var customers = await _customerService.GetAllCustomers(
customerGroupIds: model.SearchCustomerGroupIds.ToArray(),
diff --git a/src/Web/Grand.Web.Admin/Controllers/CustomerGroupController.cs b/src/Web/Grand.Web.Admin/Controllers/CustomerGroupController.cs
index e50c21c42..0ed5f31bd 100644
--- a/src/Web/Grand.Web.Admin/Controllers/CustomerGroupController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/CustomerGroupController.cs
@@ -25,14 +25,14 @@ public class CustomerGroupController : BaseAdminController
IGroupService groupService,
ITranslationService translationService,
IPermissionService permissionService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ICustomerGroupProductService customerGroupProductService)
{
_customerGroupViewModelService = customerGroupViewModelService;
_groupService = groupService;
_translationService = translationService;
_permissionService = permissionService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_customerGroupProductService = customerGroupProductService;
}
@@ -44,7 +44,7 @@ public class CustomerGroupController : BaseAdminController
private readonly IGroupService _groupService;
private readonly ITranslationService _translationService;
private readonly IPermissionService _permissionService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ICustomerGroupProductService _customerGroupProductService;
#endregion
@@ -263,7 +263,7 @@ public class CustomerGroupController : BaseAdminController
foreach (var pr in permissionRecords)
model.Add(new CustomerGroupPermissionModel {
Id = pr.Id,
- Name = _translationService.GetResource(pr.GetTranslationPermissionName(), _workContext.WorkingLanguage.Id),
+ Name = _translationService.GetResource(pr.GetTranslationPermissionName(), _workContextAccessor.WorkContext.WorkingLanguage.Id),
SystemName = pr.SystemName,
Actions = pr.Actions.ToList(),
Access = pr.CustomerGroups.Contains(customerGroupId)
diff --git a/src/Web/Grand.Web.Admin/Controllers/DiscountController.cs b/src/Web/Grand.Web.Admin/Controllers/DiscountController.cs
index 7aa760f36..22f0f993e 100644
--- a/src/Web/Grand.Web.Admin/Controllers/DiscountController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/DiscountController.cs
@@ -33,7 +33,7 @@ public class DiscountController : BaseAdminController
IDiscountViewModelService discountViewModelService,
IDiscountService discountService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IDateTimeService dateTimeService,
IGroupService groupService,
IDiscountProviderLoader discountProviderLoader,
@@ -42,7 +42,7 @@ public class DiscountController : BaseAdminController
_discountViewModelService = discountViewModelService;
_discountService = discountService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_dateTimeService = dateTimeService;
_groupService = groupService;
_discountProviderLoader = discountProviderLoader;
@@ -56,7 +56,7 @@ public class DiscountController : BaseAdminController
private readonly IDiscountViewModelService _discountViewModelService;
private readonly IDiscountService _discountService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IDateTimeService _dateTimeService;
private readonly IGroupService _groupService;
private readonly IDiscountProviderLoader _discountProviderLoader;
@@ -110,8 +110,8 @@ public class DiscountController : BaseAdminController
{
if (ModelState.IsValid)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
var discount = await _discountViewModelService.InsertDiscountModel(model);
Success(_translationService.GetResource("admin.marketing.discounts.Added"));
@@ -133,17 +133,17 @@ public class DiscountController : BaseAdminController
//No discount found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
{
if (!discount.LimitedToStores || (discount.LimitedToStores &&
- discount.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ discount.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
discount.Stores.Count > 1))
{
Warning(_translationService.GetResource("admin.marketing.discounts.Permissions"));
}
else
{
- if (!discount.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (!discount.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("List");
}
}
@@ -164,14 +164,14 @@ public class DiscountController : BaseAdminController
//No discount found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!discount.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!discount.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = discount.Id });
if (ModelState.IsValid)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
discount = await _discountViewModelService.UpdateDiscountModel(discount, model);
Success(_translationService.GetResource("admin.marketing.discounts.Updated"));
@@ -201,8 +201,8 @@ public class DiscountController : BaseAdminController
//No discount found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!discount.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!discount.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = discount.Id });
var usageHistory = await _mediator.Send(new GetDiscountUsageHistoryQuery { DiscountId = discount.Id });
@@ -603,7 +603,7 @@ public class DiscountController : BaseAdminController
DiscountModel.AddBrandToDiscountModel model, [FromServices] IBrandService brandService)
{
var brands = await brandService.GetAllBrands(model.SearchBrandName,
- _workContext.CurrentCustomer.StaffStoreId, command.Page - 1, command.PageSize, true);
+ _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId, command.Page - 1, command.PageSize, true);
var gridModel = new DataSourceResult {
Data = brands.Select(x => x.ToModel()),
diff --git a/src/Web/Grand.Web.Admin/Controllers/DownloadController.cs b/src/Web/Grand.Web.Admin/Controllers/DownloadController.cs
index a7a90265d..e77616e8a 100644
--- a/src/Web/Grand.Web.Admin/Controllers/DownloadController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/DownloadController.cs
@@ -13,12 +13,12 @@ namespace Grand.Web.Admin.Controllers;
public class DownloadController : BaseAdminController
{
private readonly IDownloadService _downloadService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public DownloadController(IDownloadService downloadService, IWorkContext workContext)
+ public DownloadController(IDownloadService downloadService, IWorkContextAccessor workContextAccessor)
{
_downloadService = downloadService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<IActionResult> DownloadFile(Guid downloadGuid)
@@ -98,7 +98,7 @@ public class DownloadController : BaseAdminController
var download = new Download {
DownloadGuid = Guid.NewGuid(),
- CustomerId = _workContext.CurrentCustomer.Id,
+ CustomerId = _workContextAccessor.WorkContext.CurrentCustomer.Id,
UseDownloadUrl = false,
DownloadUrl = "",
DownloadBinary = fileBinary,
diff --git a/src/Web/Grand.Web.Admin/Controllers/HomeController.cs b/src/Web/Grand.Web.Admin/Controllers/HomeController.cs
index d45e1528c..0493afa79 100644
--- a/src/Web/Grand.Web.Admin/Controllers/HomeController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/HomeController.cs
@@ -25,7 +25,7 @@ public class HomeController : BaseAdminController
ITranslationService translationService,
IStoreService storeService,
ICustomerService customerService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
IOrderReportService orderReportService,
IProductsReportService productsReportService,
@@ -36,7 +36,7 @@ public class HomeController : BaseAdminController
_translationService = translationService;
_storeService = storeService;
_customerService = customerService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_orderReportService = orderReportService;
_productsReportService = productsReportService;
@@ -54,8 +54,8 @@ public class HomeController : BaseAdminController
var model = new DashboardActivityModel();
var storeId = string.Empty;
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
model.OrdersPending =
(await _orderReportService.GetOrderAverageReportLine(storeId, os: (int)OrderStatusSystem.Pending))
@@ -86,7 +86,7 @@ public class HomeController : BaseAdminController
private readonly ITranslationService _translationService;
private readonly IStoreService _storeService;
private readonly ICustomerService _customerService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
private readonly IOrderReportService _orderReportService;
private readonly IProductsReportService _productsReportService;
@@ -121,8 +121,8 @@ public class HomeController : BaseAdminController
{
var language = await languageService.GetLanguageById(langid);
if (language != null)
- await _customerService.UpdateUserField(_workContext.CurrentCustomer, SystemCustomerFieldNames.LanguageId,
- language.Id, _workContext.CurrentStore.Id);
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.LanguageId,
+ language.Id, _workContextAccessor.WorkContext.CurrentStore.Id);
//home page
if (string.IsNullOrEmpty(returnUrl))
@@ -138,15 +138,15 @@ public class HomeController : BaseAdminController
if (storeid != null)
storeid = storeid.Trim();
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
returnUrl = Url.Action("Index", "Home", new { area = Constants.AreaAdmin });
var store = await _storeService.GetStoreById(storeid);
if (store != null || storeid == "")
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.AdminAreaStoreScopeConfiguration, storeid);
else
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.AdminAreaStoreScopeConfiguration, "");
//home page
@@ -199,7 +199,7 @@ public class HomeController : BaseAdminController
public async Task<IActionResult> AccessDenied()
{
- var currentCustomer = _workContext.CurrentCustomer;
+ var currentCustomer = _workContextAccessor.WorkContext.CurrentCustomer;
if (currentCustomer == null || await _groupService.IsGuest(currentCustomer))
{
_logger.LogInformation("Access denied to anonymous request");
diff --git a/src/Web/Grand.Web.Admin/Controllers/LoginController.cs b/src/Web/Grand.Web.Admin/Controllers/LoginController.cs
index 0ac5d6836..c0011de37 100644
--- a/src/Web/Grand.Web.Admin/Controllers/LoginController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/LoginController.cs
@@ -28,7 +28,7 @@ public class LoginController : BaseController
private readonly IMediator _mediator;
private readonly IMessageProviderService _messageProviderService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public LoginController(
CustomerSettings customerSettings,
@@ -38,7 +38,7 @@ public class LoginController : BaseController
ICustomerService customerService,
IGrandAuthenticationService authenticationService,
IMessageProviderService messageProviderService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator)
{
_customerSettings = customerSettings;
@@ -48,7 +48,7 @@ public class LoginController : BaseController
_customerService = customerService;
_authenticationService = authenticationService;
_messageProviderService = messageProviderService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
}
@@ -128,11 +128,11 @@ public class LoginController : BaseController
if (_customerSettings.TwoFactorAuthenticationType != TwoFactorAuthenticationType.AppVerification)
{
- await twoFactorAuthenticationService.GenerateCodeSetup("", customer, _workContext.WorkingLanguage,
+ await twoFactorAuthenticationService.GenerateCodeSetup("", customer, _workContextAccessor.WorkContext.WorkingLanguage,
_customerSettings.TwoFactorAuthenticationType);
if (_customerSettings.TwoFactorAuthenticationType == TwoFactorAuthenticationType.EmailVerification)
await _messageProviderService.SendCustomerEmailTokenValidationMessage(customer,
- _workContext.CurrentStore, _workContext.WorkingLanguage.Id);
+ _workContextAccessor.WorkContext.CurrentStore, _workContextAccessor.WorkContext.WorkingLanguage.Id);
}
return View();
diff --git a/src/Web/Grand.Web.Admin/Controllers/MerchandiseReturnController.cs b/src/Web/Grand.Web.Admin/Controllers/MerchandiseReturnController.cs
index aab38b887..272f73688 100644
--- a/src/Web/Grand.Web.Admin/Controllers/MerchandiseReturnController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/MerchandiseReturnController.cs
@@ -26,14 +26,14 @@ public class MerchandiseReturnController : BaseAdminController
ITranslationService translationService,
IMerchandiseReturnService merchandiseReturnService,
IOrderService orderService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService)
{
_merchandiseReturnViewModelService = merchandiseReturnViewModelService;
_translationService = translationService;
_merchandiseReturnService = merchandiseReturnService;
_orderService = orderService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
}
@@ -45,7 +45,7 @@ public class MerchandiseReturnController : BaseAdminController
private readonly ITranslationService _translationService;
private readonly IMerchandiseReturnService _merchandiseReturnService;
private readonly IOrderService _orderService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
#endregion Fields
@@ -68,8 +68,8 @@ public class MerchandiseReturnController : BaseAdminController
[HttpPost]
public async Task<IActionResult> List(DataSourceRequest command, MerchandiseReturnListModel model)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.StoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.StoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var merchandiseReturnModels =
await _merchandiseReturnViewModelService.PrepareMerchandiseReturnModel(model, command.Page,
command.PageSize);
@@ -96,8 +96,8 @@ public class MerchandiseReturnController : BaseAdminController
//not found
return RedirectToAction("List", "MerchandiseReturn");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- merchandiseReturn.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ merchandiseReturn.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "MerchandiseReturn");
return RedirectToAction("Edit", "MerchandiseReturn", new { id = merchandiseReturn.Id });
@@ -111,8 +111,8 @@ public class MerchandiseReturnController : BaseAdminController
if (merchandiseReturn == null)
return ErrorForKendoGridJson("Merchandise return not found");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- merchandiseReturn.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ merchandiseReturn.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return ErrorForKendoGridJson("Merchandise return is not your");
var items = await _merchandiseReturnViewModelService.PrepareMerchandiseReturnItemModel(merchandiseReturnId);
var gridModel = new DataSourceResult {
@@ -132,8 +132,8 @@ public class MerchandiseReturnController : BaseAdminController
//No merchandise return found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- merchandiseReturn.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ merchandiseReturn.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "MerchandiseReturn");
var model = new MerchandiseReturnModel();
await _merchandiseReturnViewModelService.PrepareMerchandiseReturnModel(model, merchandiseReturn, false);
@@ -154,8 +154,8 @@ public class MerchandiseReturnController : BaseAdminController
//No merchandise return found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- merchandiseReturn.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ merchandiseReturn.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "MerchandiseReturn");
if (ModelState.IsValid)
@@ -190,8 +190,8 @@ public class MerchandiseReturnController : BaseAdminController
//No merchandise return found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- merchandiseReturn.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ merchandiseReturn.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "MerchandiseReturn");
if (ModelState.IsValid)
{
@@ -216,8 +216,8 @@ public class MerchandiseReturnController : BaseAdminController
if (merchandiseReturn == null)
throw new ArgumentException("No merchandise return found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- merchandiseReturn.StoreId != _workContext.CurrentCustomer.StaffStoreId) return Content("");
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ merchandiseReturn.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return Content("");
//merchandise return notes
var merchandiseReturnNoteModels =
await _merchandiseReturnViewModelService.PrepareMerchandiseReturnNotes(merchandiseReturn);
@@ -240,8 +240,8 @@ public class MerchandiseReturnController : BaseAdminController
if (order == null)
return Json(new { Result = false });
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- merchandiseReturn.StoreId != _workContext.CurrentCustomer.StaffStoreId) return Json(new { Result = false });
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ merchandiseReturn.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return Json(new { Result = false });
await _merchandiseReturnViewModelService.InsertMerchandiseReturnNote(merchandiseReturn, order, downloadId,
displayToCustomer, message);
@@ -256,8 +256,8 @@ public class MerchandiseReturnController : BaseAdminController
if (merchandiseReturn == null)
throw new ArgumentException("No merchandise return found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- merchandiseReturn.StoreId != _workContext.CurrentCustomer.StaffStoreId) return Json(new { Result = false });
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ merchandiseReturn.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return Json(new { Result = false });
await _merchandiseReturnViewModelService.DeleteMerchandiseReturnNote(merchandiseReturn, id);
diff --git a/src/Web/Grand.Web.Admin/Controllers/NewsLetterSubscriptionController.cs b/src/Web/Grand.Web.Admin/Controllers/NewsLetterSubscriptionController.cs
index 18e3d817f..e02264baa 100644
--- a/src/Web/Grand.Web.Admin/Controllers/NewsLetterSubscriptionController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/NewsLetterSubscriptionController.cs
@@ -26,7 +26,7 @@ public class NewsLetterSubscriptionController : BaseAdminController
private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService;
private readonly IStoreService _storeService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public NewsLetterSubscriptionController(INewsLetterSubscriptionService newsLetterSubscriptionService,
INewsletterCategoryService newsletterCategoryService,
@@ -34,7 +34,7 @@ public class NewsLetterSubscriptionController : BaseAdminController
ITranslationService translationService,
IStoreService storeService,
IGroupService groupService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_newsLetterSubscriptionService = newsLetterSubscriptionService;
_newsletterCategoryService = newsletterCategoryService;
@@ -42,7 +42,7 @@ public class NewsLetterSubscriptionController : BaseAdminController
_translationService = translationService;
_storeService = storeService;
_groupService = groupService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
[NonAction]
@@ -76,7 +76,7 @@ public class NewsLetterSubscriptionController : BaseAdminController
{
var model = new NewsLetterSubscriptionListModel();
- var storeId = _workContext.CurrentCustomer.StaffStoreId;
+ var storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
//stores
model.AvailableStores.Add(new SelectListItem
@@ -123,8 +123,8 @@ public class NewsLetterSubscriptionController : BaseAdminController
break;
}
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.StoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.StoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var newsletterSubscriptions = await _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(
model.SearchEmail,
@@ -190,8 +190,8 @@ public class NewsLetterSubscriptionController : BaseAdminController
break;
}
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.StoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.StoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var subscriptions = await _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(model.SearchEmail,
model.StoreId, isActive, searchCategoryIds);
@@ -212,7 +212,7 @@ public class NewsLetterSubscriptionController : BaseAdminController
if (importcsvfile is { Length: > 0 })
{
var count = await _newsLetterSubscriptionService.ImportNewsletterSubscribersFromTxt(
- importcsvfile.OpenReadStream(), _workContext.CurrentStore.Id);
+ importcsvfile.OpenReadStream(), _workContextAccessor.WorkContext.CurrentStore.Id);
Success(string.Format(
_translationService.GetResource("admin.marketing.NewsLetterSubscriptions.ImportEmailsSuccess"),
count));
diff --git a/src/Web/Grand.Web.Admin/Controllers/OnlineCustomerController.cs b/src/Web/Grand.Web.Admin/Controllers/OnlineCustomerController.cs
index 8d40f7401..ad6c447df 100644
--- a/src/Web/Grand.Web.Admin/Controllers/OnlineCustomerController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/OnlineCustomerController.cs
@@ -20,13 +20,13 @@ public class OnlineCustomerController : BaseAdminController
IDateTimeService dateTimeService,
CustomerSettings customerSettings,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_customerService = customerService;
_dateTimeService = dateTimeService;
_customerSettings = customerSettings;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
#endregion
@@ -37,7 +37,7 @@ public class OnlineCustomerController : BaseAdminController
private readonly IDateTimeService _dateTimeService;
private readonly CustomerSettings _customerSettings;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
#endregion
@@ -54,7 +54,7 @@ public class OnlineCustomerController : BaseAdminController
{
var customers = await _customerService.GetOnlineCustomers(
DateTime.UtcNow.AddMinutes(-_customerSettings.OnlineCustomerMinutes),
- null, _workContext.CurrentCustomer.StaffStoreId, _workContext.CurrentCustomer.SeId, command.Page - 1,
+ null, _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId, _workContextAccessor.WorkContext.CurrentCustomer.SeId, command.Page - 1,
command.PageSize);
var items = new List<OnlineCustomerModel>();
foreach (var x in customers)
diff --git a/src/Web/Grand.Web.Admin/Controllers/OrderController.cs b/src/Web/Grand.Web.Admin/Controllers/OrderController.cs
index 258fe41a1..96916cac1 100644
--- a/src/Web/Grand.Web.Admin/Controllers/OrderController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/OrderController.cs
@@ -28,7 +28,7 @@ public class OrderController(
IOrderService orderService,
IOrderStatusService orderStatusService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IPdfService pdfService,
IGroupService groupService,
IExportManager<Order> exportManager,
@@ -39,8 +39,8 @@ public class OrderController(
protected virtual async Task<bool> CheckSalesManager(Order order)
{
- return await groupService.IsSalesManager(workContext.CurrentCustomer)
- && workContext.CurrentCustomer.SeId != order.SeId;
+ return await groupService.IsSalesManager(workContextAccessor.WorkContext.CurrentCustomer)
+ && workContextAccessor.WorkContext.CurrentCustomer.SeId != order.SeId;
}
#endregion
@@ -64,7 +64,7 @@ public class OrderController(
int? paymentStatusId = null, int? shippingStatusId = null, DateTime? startDate = null, string code = null)
{
var model = await orderViewModelService.PrepareOrderListModel(orderStatusId, paymentStatusId, shippingStatusId,
- startDate, workContext.CurrentCustomer.StaffStoreId, code);
+ startDate, workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId, code);
return View(model);
}
@@ -76,8 +76,8 @@ public class OrderController(
return Content("");
var storeId = string.Empty;
- if (await groupService.IsStaff(workContext.CurrentCustomer))
- storeId = workContext.CurrentCustomer.StaffStoreId;
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
//products
const int productNumber = 15;
@@ -100,8 +100,8 @@ public class OrderController(
[HttpPost]
public async Task<IActionResult> OrderList(DataSourceRequest command, OrderListModel model)
{
- if (await groupService.IsStaff(workContext.CurrentCustomer))
- model.StoreId = workContext.CurrentCustomer.StaffStoreId;
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer))
+ model.StoreId = workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var (orderModels, totalCount) =
await orderViewModelService.PrepareOrderModel(model, command.Page, command.PageSize);
@@ -133,8 +133,8 @@ public class OrderController(
if (order == null || await CheckSalesManager(order))
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
return RedirectToAction("Edit", "Order", new { id = order.Id });
}
@@ -147,8 +147,8 @@ public class OrderController(
[HttpPost]
public async Task<IActionResult> ExportExcelAll(OrderListModel model)
{
- if (await groupService.IsStaff(workContext.CurrentCustomer))
- model.StoreId = workContext.CurrentCustomer.StaffStoreId;
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer))
+ model.StoreId = workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
//load orders
var orders = await orderViewModelService.PrepareOrders(model);
@@ -178,8 +178,8 @@ public class OrderController(
orders.AddRange(await orderService.GetOrdersByIds(ids));
}
- if (await groupService.IsStaff(workContext.CurrentCustomer))
- orders = orders.Where(x => x.StoreId == workContext.CurrentCustomer.StaffStoreId).ToList();
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer))
+ orders = orders.Where(x => x.StoreId == workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId).ToList();
var bytes = await exportManager.Export(orders);
return File(bytes, "text/xls", "orders.xlsx");
}
@@ -199,8 +199,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
try
{
await mediator.Send(new CancelOrderCommand { Order = order, NotifyCustomer = true });
@@ -225,8 +225,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
try
{
@@ -253,8 +253,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
try
{
@@ -295,8 +295,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
var model = new OrderModel();
await orderViewModelService.PrepareOrderDetailsModel(model, order);
@@ -330,7 +330,7 @@ public class OrderController(
ICollection<string> selectedIds,
[FromServices] IShipmentService shipmentService)
{
- if (await groupService.IsStaff(workContext.CurrentCustomer))
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer))
return RedirectToAction("List", "Order");
if (selectedIds != null)
@@ -354,8 +354,8 @@ public class OrderController(
public async Task<IActionResult> PdfInvoice(string orderId)
{
var order = await orderService.GetOrderById(orderId);
- if ((await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId) ||
+ if ((await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) ||
await CheckSalesManager(order)) return RedirectToAction("List");
var orders = new List<Order> {
@@ -364,7 +364,7 @@ public class OrderController(
byte[] bytes;
using (var stream = new MemoryStream())
{
- await pdfService.PrintOrdersToPdf(stream, orders, workContext.WorkingLanguage.Id);
+ await pdfService.PrintOrdersToPdf(stream, orders, workContextAccessor.WorkContext.WorkingLanguage.Id);
bytes = stream.ToArray();
}
@@ -377,13 +377,13 @@ public class OrderController(
{
//load orders
var orders = await orderViewModelService.PrepareOrders(model);
- if (await groupService.IsStaff(workContext.CurrentCustomer))
- orders = orders.Where(x => x.StoreId == workContext.CurrentCustomer.StaffStoreId).ToList();
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer))
+ orders = orders.Where(x => x.StoreId == workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId).ToList();
byte[] bytes;
using (var stream = new MemoryStream())
{
- await pdfService.PrintOrdersToPdf(stream, orders, workContext.WorkingLanguage.Id, model.VendorId);
+ await pdfService.PrintOrdersToPdf(stream, orders, workContextAccessor.WorkContext.WorkingLanguage.Id, model.VendorId);
bytes = stream.ToArray();
}
@@ -404,8 +404,8 @@ public class OrderController(
orders.AddRange(await orderService.GetOrdersByIds(ids));
}
- if (await groupService.IsStaff(workContext.CurrentCustomer))
- orders = orders.Where(x => x.StoreId == workContext.CurrentCustomer.StaffStoreId).ToList();
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer))
+ orders = orders.Where(x => x.StoreId == workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId).ToList();
//ensure that we at least one order selected
if (orders.Count == 0)
@@ -417,7 +417,7 @@ public class OrderController(
byte[] bytes;
using (var stream = new MemoryStream())
{
- await pdfService.PrintOrdersToPdf(stream, orders, workContext.WorkingLanguage.Id);
+ await pdfService.PrintOrdersToPdf(stream, orders, workContextAccessor.WorkContext.WorkingLanguage.Id);
bytes = stream.ToArray();
}
@@ -433,8 +433,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId)
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("Edit", "Order", new { id });
order.OrderSubtotalInclTax = model.OrderSubtotalInclTaxValue;
@@ -471,8 +471,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId)
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("Edit", "Order", new { id });
order.ShippingMethod = model.ShippingMethod;
@@ -500,8 +500,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId)
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("Edit", "Order", new { id });
order.UserFields = model.UserFields;
@@ -525,8 +525,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId)
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("Edit", "Order", new { id });
if (order.OrderStatusId == (int)OrderStatusSystem.Cancelled)
{
@@ -591,8 +591,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId)
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("Edit", "Order", new { id });
var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == orderItemId);
@@ -618,8 +618,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId)
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("Edit", "Order", new { id });
var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == orderItemId);
@@ -648,8 +648,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId)
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("Edit", "Order", new { id });
var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == orderItemId);
@@ -676,8 +676,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId)
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("Edit", "Order", new { id });
var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == orderItemId);
@@ -704,8 +704,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId)
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("Edit", "Order", new { id });
var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == orderItemId);
@@ -734,8 +734,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId)
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("Edit", "Order", new { id = order.Id });
var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == model.OrderItemId);
@@ -761,8 +761,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId)
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("Edit", "Order", new { id = model.OrderId });
var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == model.OrderItemId);
@@ -801,7 +801,7 @@ public class OrderController(
categoryIds.Add(model.SearchCategoryId);
var storeId = string.Empty;
- if (await groupService.IsStaff(workContext.CurrentCustomer)) storeId = workContext.CurrentCustomer.StaffStoreId;
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer)) storeId = workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var gridModel = new DataSourceResult();
var products = (await productService.SearchProducts(categoryIds: categoryIds,
@@ -835,8 +835,8 @@ public class OrderController(
if (order == null || await CheckSalesManager(order))
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
var model = await orderViewModelService.PrepareAddProductToOrderModel(order, productId);
return View(model);
@@ -850,8 +850,8 @@ public class OrderController(
if (order == null || await CheckSalesManager(order))
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
var warnings = await orderViewModelService.AddProductToOrderDetails(model);
if (!warnings.Any())
@@ -878,8 +878,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
var address = new Address();
switch (billingAddress)
@@ -917,8 +917,8 @@ public class OrderController(
//No order found with the specified id
return RedirectToAction("List");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
var address = new Address();
switch (model.BillingAddress)
@@ -964,8 +964,8 @@ public class OrderController(
if (order == null || await CheckSalesManager(order))
throw new ArgumentException("No order found with the specified id");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId) return Content("");
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return Content("");
//order notes
var orderNoteModels = await orderViewModelService.PrepareOrderNotes(order);
var gridModel = new DataSourceResult {
@@ -983,8 +983,8 @@ public class OrderController(
if (order == null || await CheckSalesManager(order))
return Json(new { Result = false });
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId) return Json(new { Result = false });
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return Json(new { Result = false });
await orderViewModelService.InsertOrderNote(order, downloadId, displayToCustomer, message);
return Json(new { Result = true });
@@ -998,8 +998,8 @@ public class OrderController(
if (order == null || await CheckSalesManager(order))
throw new ArgumentException("No order found with the specified id");
- if (await groupService.IsStaff(workContext.CurrentCustomer) &&
- order.StoreId != workContext.CurrentCustomer.StaffStoreId) return Json(new { Result = false });
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return Json(new { Result = false });
await orderViewModelService.DeleteOrderNote(order, id);
diff --git a/src/Web/Grand.Web.Admin/Controllers/PageController.cs b/src/Web/Grand.Web.Admin/Controllers/PageController.cs
index a53ce1d67..9c64b6d31 100644
--- a/src/Web/Grand.Web.Admin/Controllers/PageController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/PageController.cs
@@ -24,14 +24,14 @@ public class PageController : BaseAdminController
IPageService pageService,
ILanguageService languageService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IDateTimeService dateTimeService)
{
_pageViewModelService = pageViewModelService;
_pageService = pageService;
_languageService = languageService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_dateTimeService = dateTimeService;
}
@@ -43,7 +43,7 @@ public class PageController : BaseAdminController
private readonly IPageService _pageService;
private readonly ILanguageService _languageService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IDateTimeService _dateTimeService;
#endregion Fields
@@ -128,7 +128,7 @@ public class PageController : BaseAdminController
return RedirectToAction("List");
var model = page.ToModel(_dateTimeService);
- model.Url = Url.RouteUrl("Page", new { SeName = page.GetSeName(_workContext.WorkingLanguage.Id) }, "http");
+ model.Url = Url.RouteUrl("Page", new { SeName = page.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id) }, "http");
//layouts
await _pageViewModelService.PrepareLayoutsModel(model);
//locales
@@ -169,7 +169,7 @@ public class PageController : BaseAdminController
}
//If we got this far, something failed, redisplay form
- model.Url = Url.RouteUrl("Page", new { SeName = page.GetSeName(_workContext.WorkingLanguage.Id) }, "http");
+ model.Url = Url.RouteUrl("Page", new { SeName = page.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id) }, "http");
//layouts
await _pageViewModelService.PrepareLayoutsModel(model);
return View(model);
diff --git a/src/Web/Grand.Web.Admin/Controllers/PaymentController.cs b/src/Web/Grand.Web.Admin/Controllers/PaymentController.cs
index 2375cbc1c..8460d9e2c 100644
--- a/src/Web/Grand.Web.Admin/Controllers/PaymentController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/PaymentController.cs
@@ -30,7 +30,7 @@ public class PaymentController : BaseAdminController
IShippingMethodService shippingMethodService,
ITranslationService translationService,
IServiceProvider serviceProvider,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_paymentService = paymentService;
_settingService = settingService;
@@ -38,7 +38,7 @@ public class PaymentController : BaseAdminController
_shippingMethodService = shippingMethodService;
_translationService = translationService;
_serviceProvider = serviceProvider;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
#endregion
@@ -51,7 +51,7 @@ public class PaymentController : BaseAdminController
private readonly IShippingMethodService _shippingMethodService;
private readonly ITranslationService _translationService;
private readonly IServiceProvider _serviceProvider;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
#endregion
@@ -83,7 +83,7 @@ public class PaymentController : BaseAdminController
if (plugin != null)
{
tmp.ConfigurationUrl = plugin.ConfigurationUrl();
- tmp.LogoUrl = pluginInfo.GetLogoUrl(_workContext.CurrentHost.Url);
+ tmp.LogoUrl = pluginInfo.GetLogoUrl(_workContextAccessor.WorkContext.CurrentHost.Url);
}
}
diff --git a/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.cs b/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.cs
index 799203029..953da3d6d 100644
--- a/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.cs
@@ -27,7 +27,7 @@ public class PaymentTransactionController : BaseAdminController
ITranslationService translationService,
IPaymentTransactionService paymentTransactionService,
IOrderService orderService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
IDateTimeService dateTimeService,
IMediator mediator,
@@ -36,7 +36,7 @@ public class PaymentTransactionController : BaseAdminController
_translationService = translationService;
_paymentTransactionService = paymentTransactionService;
_orderService = orderService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_dateTimeService = dateTimeService;
_mediator = mediator;
@@ -50,7 +50,7 @@ public class PaymentTransactionController : BaseAdminController
private readonly IPaymentTransactionService _paymentTransactionService;
private readonly IOrderService _orderService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
private readonly IDateTimeService _dateTimeService;
private readonly IMediator _mediator;
@@ -82,8 +82,8 @@ public class PaymentTransactionController : BaseAdminController
[HttpPost]
public async Task<IActionResult> List(DataSourceRequest command, PaymentTransactionListModel model)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.StoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.StoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
DateTime? startDateValue = model.StartDate == null
? null
: _dateTimeService.ConvertToUtcTime(model.StartDate.Value, _dateTimeService.CurrentTimeZone);
@@ -161,8 +161,8 @@ public class PaymentTransactionController : BaseAdminController
//not found
return RedirectToAction("List", "PaymentTransaction");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ paymentTransaction.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "PaymentTransaction");
return RedirectToAction("Edit", "PaymentTransaction", new { id = paymentTransaction.Id });
@@ -177,8 +177,8 @@ public class PaymentTransactionController : BaseAdminController
if (paymentTransaction == null)
return RedirectToAction("List", "PaymentTransaction");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ paymentTransaction.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "PaymentTransaction");
var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);
@@ -236,8 +236,8 @@ public class PaymentTransactionController : BaseAdminController
if (paymentTransaction == null)
return RedirectToAction("List", "PaymentTransaction");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ paymentTransaction.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "PaymentTransaction");
try
@@ -265,8 +265,8 @@ public class PaymentTransactionController : BaseAdminController
if (paymentTransaction == null)
return RedirectToAction("List", "PaymentTransaction");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ paymentTransaction.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "PaymentTransaction");
try
@@ -290,8 +290,8 @@ public class PaymentTransactionController : BaseAdminController
if (paymentTransaction == null)
return RedirectToAction("List", "PaymentTransaction");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ paymentTransaction.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "PaymentTransaction");
try
@@ -318,8 +318,8 @@ public class PaymentTransactionController : BaseAdminController
if (paymentTransaction == null)
return RedirectToAction("List", "PaymentTransaction");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ paymentTransaction.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "PaymentTransaction");
try
@@ -343,8 +343,8 @@ public class PaymentTransactionController : BaseAdminController
if (paymentTransaction == null)
return RedirectToAction("List", "PaymentTransaction");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ paymentTransaction.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "PaymentTransaction");
try
@@ -371,8 +371,8 @@ public class PaymentTransactionController : BaseAdminController
if (paymentTransaction == null)
return RedirectToAction("List", "PaymentTransaction");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ paymentTransaction.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "PaymentTransaction");
try
@@ -395,8 +395,8 @@ public class PaymentTransactionController : BaseAdminController
if (paymentTransaction == null)
return RedirectToAction("List", "PaymentTransaction");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ paymentTransaction.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "PaymentTransaction");
var model = new PaymentTransactionModel {
@@ -416,8 +416,8 @@ public class PaymentTransactionController : BaseAdminController
if (paymentTransaction == null)
return RedirectToAction("List", "PaymentTransaction");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ paymentTransaction.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "PaymentTransaction");
try
@@ -466,8 +466,8 @@ public class PaymentTransactionController : BaseAdminController
if (paymentTransaction == null)
return RedirectToAction("List", "PaymentTransaction");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ paymentTransaction.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "PaymentTransaction");
var model = new PaymentTransactionModel {
@@ -487,8 +487,8 @@ public class PaymentTransactionController : BaseAdminController
if (paymentTransaction == null)
return RedirectToAction("List", "PaymentTransaction");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ paymentTransaction.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "PaymentTransaction");
try
@@ -523,8 +523,8 @@ public class PaymentTransactionController : BaseAdminController
if (paymentTransaction == null)
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ paymentTransaction.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List", "MerchandiseReturn");
if (ModelState.IsValid)
{
diff --git a/src/Web/Grand.Web.Admin/Controllers/PermissionController.cs b/src/Web/Grand.Web.Admin/Controllers/PermissionController.cs
index b41df7fdb..4ab0836d0 100644
--- a/src/Web/Grand.Web.Admin/Controllers/PermissionController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/PermissionController.cs
@@ -18,12 +18,12 @@ public class PermissionController : BaseAdminController
{
#region Constructors
- public PermissionController(IWorkContext workContext,
+ public PermissionController(IWorkContextAccessor workContextAccessor,
IPermissionService permissionService,
IGroupService groupService,
ITranslationService translationService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_permissionService = permissionService;
_groupService = groupService;
_translationService = translationService;
@@ -33,7 +33,7 @@ public class PermissionController : BaseAdminController
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IPermissionService _permissionService;
private readonly IGroupService _groupService;
private readonly ITranslationService _translationService;
@@ -50,7 +50,7 @@ public class PermissionController : BaseAdminController
var customerGroups = await _groupService.GetAllCustomerGroups(showHidden: true);
foreach (var pr in permissionRecords.OrderBy(x => x.Category))
model.AvailablePermissions.Add(new PermissionRecordModel {
- Name =_translationService.GetResource(pr.GetTranslationPermissionName(), _workContext.WorkingLanguage.Id),
+ Name =_translationService.GetResource(pr.GetTranslationPermissionName(), _workContextAccessor.WorkContext.WorkingLanguage.Id),
SystemName = pr.SystemName,
Area = pr.Area,
Category = pr.Category,
@@ -169,7 +169,7 @@ public class PermissionController : BaseAdminController
if (permissionRecord != null)
{
model.AvailableActions = permissionRecord.Actions.ToList();
- model.PermissionName = _translationService.GetResource(permissionRecord.GetTranslationPermissionName(), _workContext.WorkingLanguage.Id);
+ model.PermissionName = _translationService.GetResource(permissionRecord.GetTranslationPermissionName(), _workContextAccessor.WorkContext.WorkingLanguage.Id);
}
else
{
diff --git a/src/Web/Grand.Web.Admin/Controllers/PluginController.cs b/src/Web/Grand.Web.Admin/Controllers/PluginController.cs
index 8bebb3e5a..9ee83531f 100644
--- a/src/Web/Grand.Web.Admin/Controllers/PluginController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/PluginController.cs
@@ -25,7 +25,7 @@ public class PluginController(
ITranslationService translationService,
ILogger<PluginController> logger,
IHostApplicationLifetime applicationLifetime,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IServiceProvider serviceProvider,
IEnumTranslationService enumTranslationService,
IWebHostEnvironment webHostEnvironment,
@@ -39,7 +39,7 @@ public class PluginController(
{
var pluginModel = PluginInfo.ToModel();
//logo
- pluginModel.LogoUrl = PluginInfo.GetLogoUrl(workContext.CurrentHost.Url);
+ pluginModel.LogoUrl = PluginInfo.GetLogoUrl(workContextAccessor.WorkContext.CurrentHost.Url);
//configuration URLs
if (PluginInfo.Installed)
@@ -162,7 +162,7 @@ public class PluginController(
Success(translationService.GetResource("Admin.Plugins.Installed"));
logger.LogInformation("The plugin has been installed by the user {CurrentCustomerEmail}",
- workContext.CurrentCustomer.Email);
+ workContextAccessor.WorkContext.CurrentCustomer.Email);
//stop application
applicationLifetime.StopApplication();
@@ -196,7 +196,7 @@ public class PluginController(
Success(translationService.GetResource("Admin.Plugins.Uninstalled"));
logger.LogInformation("The plugin has been uninstalled by the user {CurrentCustomerEmail}",
- workContext.CurrentCustomer.Email);
+ workContextAccessor.WorkContext.CurrentCustomer.Email);
//stop application
applicationLifetime.StopApplication();
@@ -236,7 +236,7 @@ public class PluginController(
Success(translationService.GetResource("Admin.Plugins.Removed"));
logger.LogInformation("The plugin has been removed by the user {CurrentCustomerEmail}",
- workContext.CurrentCustomer.Email);
+ workContextAccessor.WorkContext.CurrentCustomer.Email);
//stop application
applicationLifetime.StopApplication();
@@ -252,7 +252,7 @@ public class PluginController(
public IActionResult ReloadList()
{
logger.LogInformation("Reload list of plugins by the user {CurrentCustomerEmail}",
- workContext.CurrentCustomer.Email);
+ workContextAccessor.WorkContext.CurrentCustomer.Email);
//stop application
applicationLifetime.StopApplication();
@@ -304,7 +304,7 @@ public class PluginController(
}
logger.LogInformation("The plugin has been uploaded by the user {CurrentCustomerEmail}",
- workContext.CurrentCustomer.Email);
+ workContextAccessor.WorkContext.CurrentCustomer.Email);
//stop application
applicationLifetime.StopApplication();
diff --git a/src/Web/Grand.Web.Admin/Controllers/ProductAttributeController.cs b/src/Web/Grand.Web.Admin/Controllers/ProductAttributeController.cs
index df333bc08..816692377 100644
--- a/src/Web/Grand.Web.Admin/Controllers/ProductAttributeController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/ProductAttributeController.cs
@@ -24,7 +24,7 @@ public class ProductAttributeController : BaseAdminController
IProductAttributeService productAttributeService,
ILanguageService languageService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
SeoSettings seoSettings)
{
@@ -32,7 +32,7 @@ public class ProductAttributeController : BaseAdminController
_productAttributeService = productAttributeService;
_languageService = languageService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_seoSettings = seoSettings;
}
@@ -45,7 +45,7 @@ public class ProductAttributeController : BaseAdminController
private readonly IProductAttributeService _productAttributeService;
private readonly ILanguageService _languageService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
private readonly SeoSettings _seoSettings;
@@ -102,8 +102,8 @@ public class ProductAttributeController : BaseAdminController
string.IsNullOrEmpty(productAttribute.SeName) ? productAttribute.Name : productAttribute.SeName,
_seoSettings.ConvertNonWesternChars, _seoSettings.AllowUnicodeCharsInUrls,
_seoSettings.SeoCharConversion);
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
await _productAttributeService.InsertProductAttribute(productAttribute);
@@ -154,8 +154,8 @@ public class ProductAttributeController : BaseAdminController
string.IsNullOrEmpty(productAttribute.SeName) ? productAttribute.Name : productAttribute.SeName,
_seoSettings.ConvertNonWesternChars, _seoSettings.AllowUnicodeCharsInUrls,
_seoSettings.SeoCharConversion);
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
await _productAttributeService.UpdateProductAttribute(productAttribute);
Success(_translationService.GetResource("Admin.Catalog.Attributes.ProductAttributes.Updated"));
diff --git a/src/Web/Grand.Web.Admin/Controllers/ProductController.cs b/src/Web/Grand.Web.Admin/Controllers/ProductController.cs
index e63bbd412..8941dc5aa 100644
--- a/src/Web/Grand.Web.Admin/Controllers/ProductController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/ProductController.cs
@@ -37,7 +37,7 @@ public class ProductController : BaseAdminController
IProductViewModelService productViewModelService,
IProductService productService,
IInventoryManageService inventoryManageService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
ILanguageService languageService,
ITranslationService translationService,
@@ -50,7 +50,7 @@ public class ProductController : BaseAdminController
_productViewModelService = productViewModelService;
_productService = productService;
_inventoryManageService = inventoryManageService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_languageService = languageService;
_translationService = translationService;
@@ -68,7 +68,7 @@ public class ProductController : BaseAdminController
private readonly IProductViewModelService _productViewModelService;
private readonly IProductService _productService;
private readonly IInventoryManageService _inventoryManageService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
private readonly ILanguageService _languageService;
private readonly ITranslationService _translationService;
@@ -85,8 +85,8 @@ public class ProductController : BaseAdminController
protected async Task<(bool allow, string message)> CheckAccessToProduct(Product product)
{
if (product == null) return (false, "Product not exists");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!(!product.LimitedToStores || (product.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!(!product.LimitedToStores || (product.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
product.LimitedToStores)))
return (false, "This is not your product");
return (true, null);
@@ -130,9 +130,9 @@ public class ProductController : BaseAdminController
var product = await _productService.GetProductBySku(sku);
if (product != null)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
{
- if (!product.LimitedToStores || (product.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ if (!product.LimitedToStores || (product.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
product.LimitedToStores))
return RedirectToAction("Edit", new { id = product.Id });
return RedirectToAction("List", "Product");
@@ -181,17 +181,17 @@ public class ProductController : BaseAdminController
if (product == null)
//No product found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
{
if (!product.LimitedToStores || (product.LimitedToStores &&
- product.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ product.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
product.Stores.Count > 1))
{
Warning(_translationService.GetResource("Admin.Catalog.Products.Permissions"));
}
else
{
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("List");
}
}
@@ -224,8 +224,8 @@ public class ProductController : BaseAdminController
//No product found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = product.Id });
if (model.Ticks != product.Ticks)
@@ -264,8 +264,8 @@ public class ProductController : BaseAdminController
//No product found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = product.Id });
if (ModelState.IsValid)
@@ -297,11 +297,11 @@ public class ProductController : BaseAdminController
try
{
var originalProduct = await _productService.GetProductById(copyModel.Id, true);
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
{
originalProduct.LimitedToStores = true;
originalProduct.Stores.Clear();
- originalProduct.Stores.Add(_workContext.CurrentCustomer.StaffStoreId);
+ originalProduct.Stores.Add(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
}
var newProduct = await copyProductService.CopyProduct(originalProduct,
@@ -1146,8 +1146,8 @@ public class ProductController : BaseAdminController
});
var product = await _productService.GetProductById(objectId);
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return Json(new {
success = false,
message = "Access denied - staff permissions"
@@ -1419,8 +1419,8 @@ public class ProductController : BaseAdminController
ProductId = productId
};
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.StoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.StoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var (orderModels, totalCount) =
await orderViewModelService.PrepareOrderModel(model, command.Page, command.PageSize);
@@ -1447,8 +1447,8 @@ public class ProductController : BaseAdminController
return ErrorForKendoGridJson(permission.message);
var storeId = string.Empty;
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var productReviews = await productReviewService.GetAllProductReviews("", null,
null, null, "", storeId, productId);
@@ -1894,8 +1894,8 @@ public class ProductController : BaseAdminController
if (productAttributeMapping == null)
throw new ArgumentException("No product attribute mapping found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return ErrorForKendoGridJson(_translationService.GetResource("Admin.Catalog.Products.Permissions"));
await productAttributeService.DeleteProductAttributeMapping(productAttributeMapping, product.Id);
@@ -1982,8 +1982,8 @@ public class ProductController : BaseAdminController
if (productAttributeMapping == null)
return Content("No attribute value found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return Content(_translationService.GetResource("Admin.Catalog.Products.Permissions"));
await _productViewModelService.UpdateProductAttributeConditionModel(product, productAttributeMapping, model);
@@ -2008,8 +2008,8 @@ public class ProductController : BaseAdminController
if (productAttributeMapping == null)
throw new ArgumentException("No product attribute mapping found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!(!product.LimitedToStores || (product.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!(!product.LimitedToStores || (product.Stores.Contains(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
product.LimitedToStores)))
return Content("This is not your product");
var productAttribute =
@@ -2169,8 +2169,8 @@ public class ProductController : BaseAdminController
if (pav == null)
throw new ArgumentException("No product attribute value found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
throw new ArgumentException(_translationService.GetResource("Admin.Catalog.Products.Permissions"));
if (ModelState.IsValid)
@@ -2249,8 +2249,8 @@ public class ProductController : BaseAdminController
if (combination == null)
throw new ArgumentException("No product attribute combination found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return Content(_translationService.GetResource("Admin.Catalog.Products.Permissions"));
await productAttributeService.DeleteProductAttributeCombination(combination, productId);
@@ -2290,8 +2290,8 @@ public class ProductController : BaseAdminController
//No product found with the specified id
return RedirectToAction("List", "Product");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return Content(_translationService.GetResource("Admin.Catalog.Products.Permissions"));
var warnings = await _productViewModelService.InsertOrUpdateProductAttributeCombinationPopup(product, model);
@@ -2310,8 +2310,8 @@ public class ProductController : BaseAdminController
if (product == null)
throw new ArgumentException("No product found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return Content(_translationService.GetResource("Admin.Catalog.Products.Permissions"));
await _productViewModelService.GenerateAllAttributeCombinations(product);
@@ -2327,8 +2327,8 @@ public class ProductController : BaseAdminController
if (product == null)
throw new ArgumentException("No product found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
throw new ArgumentException(_translationService.GetResource("Admin.Catalog.Products.Permissions"));
if (ModelState.IsValid)
@@ -2381,8 +2381,8 @@ public class ProductController : BaseAdminController
if (product == null)
throw new ArgumentException("No product found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return Content("", _translationService.GetResource("Admin.Catalog.Products.Permissions"));
var combination =
@@ -2403,8 +2403,8 @@ public class ProductController : BaseAdminController
if (product == null)
throw new ArgumentException("No product found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return Content("", _translationService.GetResource("Admin.Catalog.Products.Permissions"));
var combination =
@@ -2425,8 +2425,8 @@ public class ProductController : BaseAdminController
if (product == null)
throw new ArgumentException("No product found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return ErrorForKendoGridJson(_translationService.GetResource("Admin.Catalog.Products.Permissions"));
var combination =
@@ -2488,8 +2488,8 @@ public class ProductController : BaseAdminController
if (product == null)
throw new ArgumentException("No product found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return Json(new { errors = _translationService.GetResource("Admin.Catalog.Products.Permissions") });
var reservations = await _productReservationService.GetProductReservationsByProductId(productId, null, null);
@@ -2622,8 +2622,8 @@ public class ProductController : BaseAdminController
if (product == null)
throw new ArgumentException("No product found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return Json(new { errors = _translationService.GetResource("Admin.Catalog.Products.Permissions") });
var toDelete = await _productReservationService.GetProductReservationsByProductId(productId, true, null);
@@ -2639,8 +2639,8 @@ public class ProductController : BaseAdminController
if (product == null)
throw new ArgumentException("No product found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return Json(new { errors = _translationService.GetResource("Admin.Catalog.Products.Permissions") });
var toDelete =
@@ -2659,8 +2659,8 @@ public class ProductController : BaseAdminController
if (product == null)
throw new ArgumentException("No product found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return ErrorForKendoGridJson(_translationService.GetResource("Admin.Catalog.Products.Permissions"));
var toDelete = await _productReservationService.GetProductReservation(model.ReservationId);
@@ -2689,8 +2689,8 @@ public class ProductController : BaseAdminController
if (product == null)
throw new ArgumentException("No product found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return Json(new { errors = _translationService.GetResource("Admin.Catalog.Products.Permissions") });
var (bidModels, totalCount) =
@@ -2710,8 +2710,8 @@ public class ProductController : BaseAdminController
if (product == null)
throw new ArgumentException("No product found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(_workContext.CurrentCustomer.StaffStoreId))
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return Json(new DataSourceResult
{ Errors = _translationService.GetResource("Admin.Catalog.Products.Permissions") });
diff --git a/src/Web/Grand.Web.Admin/Controllers/ProductReviewController.cs b/src/Web/Grand.Web.Admin/Controllers/ProductReviewController.cs
index a5164f879..1ee6f1fb0 100644
--- a/src/Web/Grand.Web.Admin/Controllers/ProductReviewController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/ProductReviewController.cs
@@ -21,13 +21,13 @@ public class ProductReviewController : BaseAdminController
IProductReviewViewModelService productReviewViewModelService,
IProductReviewService productReviewService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService)
{
_productReviewViewModelService = productReviewViewModelService;
_productReviewService = productReviewService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
}
@@ -38,7 +38,7 @@ public class ProductReviewController : BaseAdminController
private readonly IProductReviewViewModelService _productReviewViewModelService;
private readonly IProductReviewService _productReviewService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
#endregion Fields
@@ -53,7 +53,7 @@ public class ProductReviewController : BaseAdminController
public async Task<IActionResult> List()
{
- var model = await _productReviewViewModelService.PrepareProductReviewListModel(_workContext.CurrentCustomer
+ var model = await _productReviewViewModelService.PrepareProductReviewListModel(_workContextAccessor.WorkContext.CurrentCustomer
.StaffStoreId);
return View(model);
}
@@ -63,8 +63,8 @@ public class ProductReviewController : BaseAdminController
public async Task<IActionResult> List(DataSourceRequest command, ProductReviewListModel model)
{
//limit for store manager
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.SearchStoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.SearchStoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var (productReviewModels, totalCount) =
await _productReviewViewModelService.PrepareProductReviewsModel(model, command.Page, command.PageSize);
@@ -86,8 +86,8 @@ public class ProductReviewController : BaseAdminController
//No product review found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- productReview.StoreId != _workContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ productReview.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
var model = new ProductReviewModel();
await _productReviewViewModelService.PrepareProductReviewModel(model, productReview, false, false);
@@ -104,8 +104,8 @@ public class ProductReviewController : BaseAdminController
//No product review found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- productReview.StoreId != _workContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ productReview.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
if (ModelState.IsValid)
{
@@ -131,8 +131,8 @@ public class ProductReviewController : BaseAdminController
//No product review found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- productReview.StoreId != _workContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ productReview.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return RedirectToAction("List");
if (ModelState.IsValid)
{
@@ -151,7 +151,7 @@ public class ProductReviewController : BaseAdminController
{
if (selectedIds != null)
await _productReviewViewModelService.ApproveSelected(selectedIds.ToList(),
- _workContext.CurrentCustomer.StaffStoreId);
+ _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
return Json(new { Result = true });
}
@@ -162,7 +162,7 @@ public class ProductReviewController : BaseAdminController
{
if (selectedIds != null)
await _productReviewViewModelService.DisapproveSelected(selectedIds.ToList(),
- _workContext.CurrentCustomer.StaffStoreId);
+ _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
return Json(new { Result = true });
}
@@ -176,8 +176,8 @@ public class ProductReviewController : BaseAdminController
return Content("");
var storeId = string.Empty;
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
//products
const int productNumber = 15;
diff --git a/src/Web/Grand.Web.Admin/Controllers/ReportsController.cs b/src/Web/Grand.Web.Admin/Controllers/ReportsController.cs
index 995e4b189..92a7769eb 100644
--- a/src/Web/Grand.Web.Admin/Controllers/ReportsController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/ReportsController.cs
@@ -52,7 +52,7 @@ public class ReportsController : BaseAdminController
private readonly IStoreService _storeService;
private readonly ITranslationService _translationService;
private readonly IVendorService _vendorService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IEnumTranslationService _enumTranslationService;
public ReportsController(IOrderService orderService,
IOrderReportService orderReportService,
@@ -60,7 +60,7 @@ public class ReportsController : BaseAdminController
ICustomerReportService customerReportService,
ICustomerReportViewModelService customerReportViewModelService,
IPermissionService permissionService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IPriceFormatter priceFormatter,
IProductService productService,
IProductAttributeFormatter productAttributeFormatter,
@@ -82,7 +82,7 @@ public class ReportsController : BaseAdminController
_customerReportService = customerReportService;
_customerReportViewModelService = customerReportViewModelService;
_permissionService = permissionService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_priceFormatter = priceFormatter;
_productService = productService;
_productAttributeFormatter = productAttributeFormatter;
@@ -104,8 +104,8 @@ public class ReportsController : BaseAdminController
int pageSize, int orderBy)
{
var storeId = "";
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var items = await _orderReportService.BestSellersReport(
storeId,
@@ -140,7 +140,7 @@ public class ReportsController : BaseAdminController
{
var report = new List<OrderPeriodReportLineModel>();
var reportperiod7days =
- await _orderReportService.GetOrderPeriodReport(7, _workContext.CurrentCustomer.StaffStoreId);
+ await _orderReportService.GetOrderPeriodReport(7, _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
report.Add(new OrderPeriodReportLineModel {
Period = _translationService.GetResource("Admin.Reports.Period.7days"),
Count = reportperiod7days.Count,
@@ -148,7 +148,7 @@ public class ReportsController : BaseAdminController
});
var reportperiod14days =
- await _orderReportService.GetOrderPeriodReport(14, _workContext.CurrentCustomer.StaffStoreId);
+ await _orderReportService.GetOrderPeriodReport(14, _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
report.Add(new OrderPeriodReportLineModel {
Period = _translationService.GetResource("Admin.Reports.Period.14days"),
Count = reportperiod14days.Count,
@@ -156,7 +156,7 @@ public class ReportsController : BaseAdminController
});
var reportperiodmonth =
- await _orderReportService.GetOrderPeriodReport(30, _workContext.CurrentCustomer.StaffStoreId);
+ await _orderReportService.GetOrderPeriodReport(30, _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
report.Add(new OrderPeriodReportLineModel {
Period = _translationService.GetResource("Admin.Reports.Period.month"),
Count = reportperiodmonth.Count,
@@ -164,7 +164,7 @@ public class ReportsController : BaseAdminController
});
var reportperiodyear =
- await _orderReportService.GetOrderPeriodReport(365, _workContext.CurrentCustomer.StaffStoreId);
+ await _orderReportService.GetOrderPeriodReport(365, _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
report.Add(new OrderPeriodReportLineModel {
Period = _translationService.GetResource("Admin.Reports.Period.year"),
Count = reportperiodyear.Count,
@@ -204,8 +204,8 @@ public class ReportsController : BaseAdminController
var model = new BestsellersReportModel();
var storeId = "";
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
//stores
model.AvailableStores.Add(new SelectListItem
@@ -245,8 +245,8 @@ public class ReportsController : BaseAdminController
[HttpPost]
public async Task<IActionResult> BestsellersReportList(DataSourceRequest command, BestsellersReportModel model)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.StoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.StoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
DateTime? startDateValue = model.StartDate == null
? null
@@ -319,8 +319,8 @@ public class ReportsController : BaseAdminController
return Content("");
var storeId = "";
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var model = await _orderReportService.GetOrderByTimeReport(storeId, startDate, endDate);
var gridModel = new DataSourceResult {
@@ -347,8 +347,8 @@ public class ReportsController : BaseAdminController
: _dateTimeService.ConvertToUtcTime(model.EndDate.Value, _dateTimeService.CurrentTimeZone).AddDays(1);
var storeId = "";
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var items = await _orderReportService.ProductsNeverSold(storeId, "",
startDateValue, endDateValue,
@@ -372,8 +372,8 @@ public class ReportsController : BaseAdminController
return Content("");
var storeId = "";
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var report = new List<OrderAverageReportLineSummary> {
await _orderReportService.OrderAverageReport(storeId, (int)OrderStatusSystem.Pending),
@@ -413,8 +413,8 @@ public class ReportsController : BaseAdminController
if (!await _permissionService.Authorize(StandardPermission.ManageOrders))
return Content("");
var storeId = "";
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
//load orders
var orders = await _orderService.SearchOrders(
@@ -459,8 +459,8 @@ public class ReportsController : BaseAdminController
return Content("");
var storeId = "";
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var model = new List<OrderIncompleteReportLineModel>();
@@ -543,8 +543,8 @@ public class ReportsController : BaseAdminController
var paymentStatus = model.PaymentStatusId > 0 ? (PaymentStatus?)model.PaymentStatusId : null;
var storeId = "";
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var items = await _orderReportService.GetCountryReport(
storeId,
@@ -600,8 +600,8 @@ public class ReportsController : BaseAdminController
public async Task<IActionResult> LowStockReportList(DataSourceRequest command)
{
var storeId = "";
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var lowStockProducts = await _productsReportService.LowStockProducts(storeId: storeId);
@@ -627,7 +627,7 @@ public class ReportsController : BaseAdminController
Id = product.Id,
Name = product.Name,
Attributes = await _productAttributeFormatter.FormatAttributes(product, combination.Attributes,
- _workContext.CurrentCustomer, "<br />", true, true, true, false),
+ _workContextAccessor.WorkContext.CurrentCustomer, "<br />", true, true, true, false),
ManageInventoryMethod = _enumTranslationService.GetTranslationEnum(product.ManageInventoryMethodId),
StockQuantity = combination.StockQuantity,
Published = product.Published
@@ -660,8 +660,8 @@ public class ReportsController : BaseAdminController
public async Task<IActionResult> ReportBestCustomersByOrderTotalList(DataSourceRequest command,
BestCustomersReportModel model)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.StoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.StoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var (bestCustomerReportLineModels, totalCount) =
await _customerReportViewModelService.PrepareBestCustomerReportLineModel(model, 1, command.Page,
@@ -677,8 +677,8 @@ public class ReportsController : BaseAdminController
public async Task<IActionResult> ReportBestCustomersByNumberOfOrdersList(DataSourceRequest command,
BestCustomersReportModel model)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.StoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.StoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var (bestCustomerReportLineModels, totalCount) =
await _customerReportViewModelService.PrepareBestCustomerReportLineModel(model, 2, command.Page,
@@ -694,8 +694,8 @@ public class ReportsController : BaseAdminController
public async Task<IActionResult> ReportRegisteredCustomersList(DataSourceRequest command)
{
var storeId = "";
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var model = await _customerReportViewModelService.GetReportRegisteredCustomersModel(storeId);
var gridModel = new DataSourceResult {
@@ -711,8 +711,8 @@ public class ReportsController : BaseAdminController
DateTime? endDate)
{
var storeId = "";
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var model = await _customerReportService.GetCustomerByTimeReport(storeId, startDate, endDate);
var gridModel = new DataSourceResult {
diff --git a/src/Web/Grand.Web.Admin/Controllers/SearchController.cs b/src/Web/Grand.Web.Admin/Controllers/SearchController.cs
index 9b074a13f..47cdb8e20 100644
--- a/src/Web/Grand.Web.Admin/Controllers/SearchController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/SearchController.cs
@@ -39,13 +39,13 @@ public class SearchController : BaseAdminController
private readonly IStoreService _storeService;
private readonly ITranslationService _translationService;
private readonly IVendorService _vendorService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public SearchController(IProductService productService, ICategoryService categoryService,
IBrandService brandService, ICollectionService collectionService,
IPageService pageService, INewsService newsService, IBlogService blogService, ICustomerService customerService,
IOrderService orderService,
- AdminSearchSettings adminSearchSettings, ITranslationService translationService, IWorkContext workContext,
+ AdminSearchSettings adminSearchSettings, ITranslationService translationService, IWorkContextAccessor workContextAccessor,
IGroupService groupService,
IStoreService storeService, IVendorService vendorService)
{
@@ -60,7 +60,7 @@ public class SearchController : BaseAdminController
_orderService = orderService;
_adminSearchSettings = adminSearchSettings;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_storeService = storeService;
_vendorService = vendorService;
@@ -72,7 +72,7 @@ public class SearchController : BaseAdminController
if (string.IsNullOrEmpty(searchTerm))
return Json("error");
- if (!await _groupService.IsAdmin(_workContext.CurrentCustomer)) return Json("Access Denied");
+ if (!await _groupService.IsAdmin(_workContextAccessor.WorkContext.CurrentCustomer)) return Json("Access Denied");
//object = actual result, int = display order for sorting
var result = new List<Tuple<object, int>>();
@@ -94,7 +94,7 @@ public class SearchController : BaseAdminController
{
var categories = await _categoryService.GetAllCategories(categoryName: searchTerm,
pageSize: _adminSearchSettings.MaxSearchResultsCount - result.Count, showHidden:
- await _groupService.IsAdmin(_workContext.CurrentCustomer));
+ await _groupService.IsAdmin(_workContextAccessor.WorkContext.CurrentCustomer));
foreach (var category in categories)
result.Add(new Tuple<object, int>(new {
title = category.Name,
@@ -247,7 +247,7 @@ public class SearchController : BaseAdminController
return model;
}
- var storeId = _workContext.CurrentCustomer.StaffStoreId;
+ var storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var categories = await _categoryService.GetAllCategories(
storeId: storeId,
@@ -286,7 +286,7 @@ public class SearchController : BaseAdminController
return model;
}
- var storeId = _workContext.CurrentCustomer.StaffStoreId;
+ var storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var collections = await _collectionService.GetAllCollections(
storeId: storeId,
@@ -363,7 +363,7 @@ public class SearchController : BaseAdminController
}
var groups = await _storeService.GetAllStores();
- var storeId = _workContext.CurrentCustomer.StaffStoreId;
+ var storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
if (!string.IsNullOrEmpty(storeId))
groups = groups.Where(x => x.Id == storeId).ToList();
diff --git a/src/Web/Grand.Web.Admin/Controllers/ShipmentController.cs b/src/Web/Grand.Web.Admin/Controllers/ShipmentController.cs
index 624afb463..77e9ee9c5 100644
--- a/src/Web/Grand.Web.Admin/Controllers/ShipmentController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/ShipmentController.cs
@@ -26,7 +26,7 @@ public class ShipmentController : BaseAdminController
IShipmentViewModelService shipmentViewModelService,
IOrderService orderService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
IPdfService pdfService,
IShipmentService shipmentService,
@@ -36,7 +36,7 @@ public class ShipmentController : BaseAdminController
_shipmentViewModelService = shipmentViewModelService;
_orderService = orderService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_pdfService = pdfService;
_shipmentService = shipmentService;
@@ -49,7 +49,7 @@ public class ShipmentController : BaseAdminController
private readonly IShipmentViewModelService _shipmentViewModelService;
private readonly IOrderService _orderService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
private readonly IPdfService _pdfService;
private readonly IShipmentService _shipmentService;
@@ -70,8 +70,8 @@ public class ShipmentController : BaseAdminController
[HttpPost]
public async Task<IActionResult> ShipmentListSelect(DataSourceRequest command, ShipmentListModel model)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.StoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.StoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var shipments = await _shipmentViewModelService.PrepareShipments(model, command.Page, command.PageSize);
var items = new List<ShipmentModel>();
@@ -93,8 +93,8 @@ public class ShipmentController : BaseAdminController
if (order == null)
throw new ArgumentException("No order found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- order.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return Content("");
//shipments
@@ -124,8 +124,8 @@ public class ShipmentController : BaseAdminController
if (order == null)
throw new ArgumentException("No order found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- shipment.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ shipment.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return Content("");
//shipments
@@ -146,8 +146,8 @@ public class ShipmentController : BaseAdminController
//No order found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- order.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List");
var model = await _shipmentViewModelService.PrepareShipmentModel(order);
@@ -165,8 +165,8 @@ public class ShipmentController : BaseAdminController
//No order found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- order.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ order.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List");
var orderItems = order.OrderItems;
@@ -215,8 +215,8 @@ public class ShipmentController : BaseAdminController
//No shipment found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- shipment.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ shipment.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List");
var orderId = shipment.OrderId;
@@ -238,8 +238,8 @@ public class ShipmentController : BaseAdminController
//No shipment found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- shipment.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ shipment.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List");
var orderId = shipment.OrderId;
@@ -272,8 +272,8 @@ public class ShipmentController : BaseAdminController
//No shipment found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- shipment.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ shipment.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List");
var order = await _orderService.GetOrderById(shipment.OrderId);
@@ -296,8 +296,8 @@ public class ShipmentController : BaseAdminController
//No shipment found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- shipment.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ shipment.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List");
var order = await _orderService.GetOrderById(shipment.OrderId);
@@ -320,8 +320,8 @@ public class ShipmentController : BaseAdminController
//No shipment found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- shipment.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ shipment.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List");
var order = await _orderService.GetOrderById(shipment.OrderId);
@@ -350,8 +350,8 @@ public class ShipmentController : BaseAdminController
//No shipment found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- shipment.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ shipment.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List");
var order = await _orderService.GetOrderById(shipment.OrderId);
@@ -383,8 +383,8 @@ public class ShipmentController : BaseAdminController
//No shipment found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- shipment.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ shipment.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List");
var order = await _orderService.GetOrderById(shipment.OrderId);
@@ -415,8 +415,8 @@ public class ShipmentController : BaseAdminController
//No shipment found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- shipment.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ shipment.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List");
var order = await _orderService.GetOrderById(shipment.OrderId);
@@ -449,8 +449,8 @@ public class ShipmentController : BaseAdminController
//No order found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- shipment.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ shipment.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("ShipmentDetails", new { id = shipment.Id });
shipment.UserFields = model.UserFields;
@@ -470,8 +470,8 @@ public class ShipmentController : BaseAdminController
//no shipment found with the specified id
return RedirectToAction("List");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- shipment.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ shipment.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return RedirectToAction("List");
var order = await _orderService.GetOrderById(shipment.OrderId);
@@ -486,7 +486,7 @@ public class ShipmentController : BaseAdminController
byte[] bytes;
using (var stream = new MemoryStream())
{
- await _pdfService.PrintPackagingSlipsToPdf(stream, shipments, _workContext.WorkingLanguage.Id);
+ await _pdfService.PrintPackagingSlipsToPdf(stream, shipments, _workContextAccessor.WorkContext.WorkingLanguage.Id);
bytes = stream.ToArray();
}
@@ -497,8 +497,8 @@ public class ShipmentController : BaseAdminController
[HttpPost]
public async Task<IActionResult> PdfPackagingSlipAll(ShipmentListModel model)
{
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.StoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.StoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
//load shipments
var shipments = await _shipmentViewModelService.PrepareShipments(model, 1, 100);
@@ -514,7 +514,7 @@ public class ShipmentController : BaseAdminController
using (var stream = new MemoryStream())
{
await _pdfService.PrintPackagingSlipsToPdf(stream, shipments.shipments.ToList(),
- _workContext.WorkingLanguage.Id);
+ _workContextAccessor.WorkContext.WorkingLanguage.Id);
bytes = stream.ToArray();
}
@@ -537,8 +537,8 @@ public class ShipmentController : BaseAdminController
}
var storeId = "";
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
shipments_access = shipments.Where(x => x.StoreId == storeId || string.IsNullOrEmpty(storeId)).ToList();
//ensure that we at least one shipment selected
@@ -551,7 +551,7 @@ public class ShipmentController : BaseAdminController
byte[] bytes;
using (var stream = new MemoryStream())
{
- await _pdfService.PrintPackagingSlipsToPdf(stream, shipments_access, _workContext.WorkingLanguage.Id);
+ await _pdfService.PrintPackagingSlipsToPdf(stream, shipments_access, _workContextAccessor.WorkContext.WorkingLanguage.Id);
bytes = stream.ToArray();
}
@@ -567,8 +567,8 @@ public class ShipmentController : BaseAdminController
if (selectedIds != null) shipments.AddRange(await _shipmentService.GetShipmentsByIds(selectedIds.ToArray()));
var storeId = "";
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
shipments_access = shipments.Where(x => x.StoreId == storeId || string.IsNullOrEmpty(storeId)).ToList();
foreach (var shipment in shipments_access)
@@ -593,8 +593,8 @@ public class ShipmentController : BaseAdminController
if (selectedIds != null) shipments.AddRange(await _shipmentService.GetShipmentsByIds(selectedIds.ToArray()));
var storeId = "";
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- storeId = _workContext.CurrentCustomer.StaffStoreId;
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
shipments_access = shipments.Where(x => x.StoreId == storeId || string.IsNullOrEmpty(storeId)).ToList();
foreach (var shipment in shipments_access)
try
@@ -619,8 +619,8 @@ public class ShipmentController : BaseAdminController
if (shipment == null)
throw new ArgumentException("No shipment found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- shipment.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ shipment.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return Content("");
//shipment notes
@@ -640,8 +640,8 @@ public class ShipmentController : BaseAdminController
if (shipment == null)
return Json(new { Result = false });
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- shipment.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ shipment.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return Json(new { Result = false });
await _shipmentViewModelService.InsertShipmentNote(shipment, downloadId, displayToCustomer, message);
@@ -657,8 +657,8 @@ public class ShipmentController : BaseAdminController
if (shipment == null)
throw new ArgumentException("No shipment found with the specified id");
- if (await _groupService.IsStaff(_workContext.CurrentCustomer) &&
- shipment.StoreId != _workContext.CurrentCustomer.StaffStoreId)
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer) &&
+ shipment.StoreId != _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
return Json(new { Result = false });
await _shipmentViewModelService.DeleteShipmentNote(shipment, id);
diff --git a/src/Web/Grand.Web.Admin/Controllers/SpecificationAttributeController.cs b/src/Web/Grand.Web.Admin/Controllers/SpecificationAttributeController.cs
index 46b1d7475..5c39e0464 100644
--- a/src/Web/Grand.Web.Admin/Controllers/SpecificationAttributeController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/SpecificationAttributeController.cs
@@ -23,7 +23,7 @@ public class SpecificationAttributeController : BaseAdminController
ISpecificationAttributeService specificationAttributeService,
ILanguageService languageService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
IProductService productService,
SeoSettings seoSettings)
@@ -31,7 +31,7 @@ public class SpecificationAttributeController : BaseAdminController
_specificationAttributeService = specificationAttributeService;
_languageService = languageService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_productService = productService;
_seoSettings = seoSettings;
@@ -54,8 +54,8 @@ public class SpecificationAttributeController : BaseAdminController
var searchStoreId = string.Empty;
//limit for store manager
- if (!string.IsNullOrEmpty(_workContext.CurrentCustomer.StaffStoreId))
- searchStoreId = _workContext.CurrentCustomer.StaffStoreId;
+ if (!string.IsNullOrEmpty(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
+ searchStoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var specificationProducts = new List<SpecificationAttributeModel.UsedByProductModel>();
var total = 0;
@@ -103,7 +103,7 @@ public class SpecificationAttributeController : BaseAdminController
private readonly IProductService _productService;
private readonly ILanguageService _languageService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
private readonly SeoSettings _seoSettings;
@@ -160,8 +160,8 @@ public class SpecificationAttributeController : BaseAdminController
? specificationAttribute.Name
: specificationAttribute.SeName, _seoSettings.ConvertNonWesternChars,
_seoSettings.AllowUnicodeCharsInUrls, _seoSettings.SeoCharConversion);
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
await _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute);
Success(_translationService.GetResource("Admin.Catalog.Attributes.SpecificationAttributes.Added"));
@@ -211,8 +211,8 @@ public class SpecificationAttributeController : BaseAdminController
? specificationAttribute.Name
: specificationAttribute.SeName, _seoSettings.ConvertNonWesternChars,
_seoSettings.AllowUnicodeCharsInUrls, _seoSettings.SeoCharConversion);
- if (await _groupService.IsStaff(_workContext.CurrentCustomer))
- model.Stores = [_workContext.CurrentCustomer.StaffStoreId];
+ if (await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
await _specificationAttributeService.UpdateSpecificationAttribute(specificationAttribute);
Success(_translationService.GetResource("Admin.Catalog.Attributes.SpecificationAttributes.Updated"));
diff --git a/src/Web/Grand.Web.Admin/Controllers/SystemController.cs b/src/Web/Grand.Web.Admin/Controllers/SystemController.cs
index 087c40ae1..944ee5854 100644
--- a/src/Web/Grand.Web.Admin/Controllers/SystemController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/SystemController.cs
@@ -32,7 +32,7 @@ public class SystemController : BaseAdminController
ICurrencyService currencyService,
IMeasureService measureService,
IDateTimeService dateTimeService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ITranslationService translationService,
IHostApplicationLifetime applicationLifetime,
IWebHostEnvironment webHostEnvironment,
@@ -48,7 +48,7 @@ public class SystemController : BaseAdminController
_currencySettings = currencySettings;
_measureSettings = measureSettings;
_dateTimeService = dateTimeService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_translationService = translationService;
_applicationLifetime = applicationLifetime;
_webHostEnvironment = webHostEnvironment;
@@ -66,7 +66,7 @@ public class SystemController : BaseAdminController
private readonly ICurrencyService _currencyService;
private readonly IMeasureService _measureService;
private readonly IDateTimeService _dateTimeService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ITranslationService _translationService;
private readonly IHostApplicationLifetime _applicationLifetime;
private readonly IWebHostEnvironment _webHostEnvironment;
@@ -120,7 +120,7 @@ public class SystemController : BaseAdminController
});
//current host
- var currenthostName = _workContext.CurrentHost.HostName;
+ var currenthostName = _workContextAccessor.WorkContext.CurrentHost.HostName;
if (!string.IsNullOrEmpty(currenthostName) &&
currenthostName.Equals(HttpContext.Request.Host.Value, StringComparison.OrdinalIgnoreCase))
model.SystemWarnings.Add(new SystemInfoModel.SystemWarningModel {
@@ -261,7 +261,7 @@ public class SystemController : BaseAdminController
public async Task<IActionResult> ClearCache(string returnUrl, [FromServices] ICacheBase cacheBase)
{
- _logger.LogInformation($"Clear cache has been done by the user: {_workContext.CurrentCustomer.Email}");
+ _logger.LogInformation($"Clear cache has been done by the user: {_workContextAccessor.WorkContext.CurrentCustomer.Email}");
await cacheBase.Clear();
@@ -277,7 +277,7 @@ public class SystemController : BaseAdminController
public IActionResult RestartApplication(string returnUrl = "")
{
- _logger.LogInformation($"The application has been restarted by the user {_workContext.CurrentCustomer.Email}");
+ _logger.LogInformation($"The application has been restarted by the user {_workContextAccessor.WorkContext.CurrentCustomer.Email}");
//stop application
_applicationLifetime.StopApplication();
diff --git a/src/Web/Grand.Web.Admin/Controllers/VendorReviewController.cs b/src/Web/Grand.Web.Admin/Controllers/VendorReviewController.cs
index 2e3bc910b..f82becfdc 100644
--- a/src/Web/Grand.Web.Admin/Controllers/VendorReviewController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/VendorReviewController.cs
@@ -22,13 +22,13 @@ public class VendorReviewController : BaseAdminController
IVendorService vendorService,
ITranslationService translationService,
IGroupService groupService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_vendorViewModelService = vendorViewModelService;
_vendorService = vendorService;
_translationService = translationService;
_groupService = groupService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
#endregion
@@ -38,7 +38,7 @@ public class VendorReviewController : BaseAdminController
private readonly IVendorViewModelService _vendorViewModelService;
private readonly IVendorService _vendorService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
#endregion Fields
diff --git a/src/Web/Grand.Web.Admin/Services/AffiliateViewModelService.cs b/src/Web/Grand.Web.Admin/Services/AffiliateViewModelService.cs
index f2d9792f5..c4c387cc1 100644
--- a/src/Web/Grand.Web.Admin/Services/AffiliateViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/AffiliateViewModelService.cs
@@ -31,16 +31,16 @@ public class AffiliateViewModelService : IAffiliateViewModelService
private readonly IPriceFormatter _priceFormatter;
private readonly SeoSettings _seoSettings;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IEnumTranslationService _enumTranslationService;
- public AffiliateViewModelService(IWorkContext workContext, ICountryService countryService,
+ public AffiliateViewModelService(IWorkContextAccessor workContextAccessor, ICountryService countryService,
IPriceFormatter priceFormatter, IAffiliateService affiliateService,
ICustomerService customerService, IOrderService orderService, ITranslationService translationService,
IDateTimeService dateTimeService,
IOrderStatusService orderStatusService,
SeoSettings seoSettings, ICurrencyService currencyService, IEnumTranslationService enumTranslationService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_countryService = countryService;
_priceFormatter = priceFormatter;
_affiliateService = affiliateService;
@@ -64,9 +64,9 @@ public class AffiliateViewModelService : IAffiliateViewModelService
model.Id = affiliate.Id;
model.Name = affiliate.Name;
- var host = _workContext.CurrentHost == null
- ? _workContext.CurrentStore.Url.TrimEnd('/')
- : _workContext.CurrentHost.Url.TrimEnd('/');
+ var host = _workContextAccessor.WorkContext.CurrentHost == null
+ ? _workContextAccessor.WorkContext.CurrentStore.Url.TrimEnd('/')
+ : _workContextAccessor.WorkContext.CurrentHost.Url.TrimEnd('/');
model.Url = affiliate.GenerateUrl(host);
if (!excludeProperties)
{
diff --git a/src/Web/Grand.Web.Admin/Services/BlogViewModelService.cs b/src/Web/Grand.Web.Admin/Services/BlogViewModelService.cs
index 2ded73f22..058c67b74 100644
--- a/src/Web/Grand.Web.Admin/Services/BlogViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/BlogViewModelService.cs
@@ -31,7 +31,7 @@ public class BlogViewModelService : IBlogViewModelService
private readonly IStoreService _storeService;
private readonly ITranslationService _translationService;
private readonly IVendorService _vendorService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ISeNameService _seNameService;
private readonly IEnumTranslationService _enumTranslationService;
@@ -44,7 +44,7 @@ public class BlogViewModelService : IBlogViewModelService
ITranslationService translationService,
IProductService productService,
IVendorService vendorService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ISeNameService seNameService,
IEnumTranslationService enumTranslationService)
{
@@ -56,7 +56,7 @@ public class BlogViewModelService : IBlogViewModelService
_translationService = translationService;
_productService = productService;
_vendorService = vendorService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_seNameService = seNameService;
_enumTranslationService = enumTranslationService;
}
@@ -64,7 +64,7 @@ public class BlogViewModelService : IBlogViewModelService
public virtual async Task<(IEnumerable<BlogPostModel> blogPosts, int totalCount)> PrepareBlogPostsModel(
int pageIndex, int pageSize)
{
- var blogPosts = await _blogService.GetAllBlogPosts(_workContext.CurrentCustomer.StaffStoreId, null, null,
+ var blogPosts = await _blogService.GetAllBlogPosts(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId, null, null,
pageIndex - 1, pageSize, true);
return (blogPosts.Select(x =>
{
@@ -127,9 +127,9 @@ public class BlogViewModelService : IBlogViewModelService
PrepareBlogPostCommentsModel(string filterByBlogPostId, int pageIndex, int pageSize)
{
IList<BlogComment> comments;
- var storeId = string.IsNullOrEmpty(_workContext.CurrentCustomer.StaffStoreId)
+ var storeId = string.IsNullOrEmpty(_workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId)
? ""
- : _workContext.CurrentCustomer.StaffStoreId;
+ : _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
if (!string.IsNullOrEmpty(filterByBlogPostId))
{
//filter comments by blog
@@ -185,7 +185,7 @@ public class BlogViewModelService : IBlogViewModelService
};
//stores
- var storeId = _workContext.CurrentCustomer.StaffStoreId;
+ var storeId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
model.AvailableStores.Add(new SelectListItem
{ Text = _translationService.GetResource("Admin.Common.All"), Value = " " });
foreach (var s in (await _storeService.GetAllStores()).Where(x =>
@@ -209,7 +209,7 @@ public class BlogViewModelService : IBlogViewModelService
public virtual async Task<(IList<ProductModel> products, int totalCount)> PrepareProductModel(
BlogProductModel.AddProductModel model, int pageIndex, int pageSize)
{
- model.SearchStoreId = _workContext.CurrentCustomer.StaffStoreId;
+ model.SearchStoreId = _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var products = await _productService.PrepareProductList(model.SearchCategoryId, model.SearchBrandId,
model.SearchCollectionId, model.SearchStoreId, model.SearchVendorId, model.SearchProductTypeId,
model.SearchProductName, pageIndex, pageSize);
diff --git a/src/Web/Grand.Web.Admin/Services/BrandViewModelService.cs b/src/Web/Grand.Web.Admin/Services/BrandViewModelService.cs
index 2bfd2fc4c..3be02c66e 100644
--- a/src/Web/Grand.Web.Admin/Services/BrandViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/BrandViewModelService.cs
@@ -26,7 +26,7 @@ public class BrandViewModelService : IBrandViewModelService
private readonly IPictureService _pictureService;
private readonly IDiscountService _discountService;
private readonly IDateTimeService _dateTimeService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ISeNameService _seNameService;
private readonly IEnumTranslationService _enumTranslationService;
@@ -40,7 +40,7 @@ public class BrandViewModelService : IBrandViewModelService
IPictureService pictureService,
IDiscountService discountService,
IDateTimeService dateTimeService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ISeNameService seNameService,
IEnumTranslationService enumTranslationService)
{
@@ -49,7 +49,7 @@ public class BrandViewModelService : IBrandViewModelService
_pictureService = pictureService;
_discountService = discountService;
_dateTimeService = dateTimeService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_seNameService = seNameService;
_enumTranslationService = enumTranslationService;
}
@@ -82,7 +82,7 @@ public class BrandViewModelService : IBrandViewModelService
ArgumentNullException.ThrowIfNull(model);
model.AvailableDiscounts = (await _discountService
- .GetDiscountsQuery(DiscountType.AssignedToBrands, _workContext.CurrentCustomer.Id))
+ .GetDiscountsQuery(DiscountType.AssignedToBrands, _workContextAccessor.WorkContext.CurrentCustomer.Id))
.Select(d => d.ToModel(_dateTimeService))
.ToList();
diff --git a/src/Web/Grand.Web.Admin/Services/CollectionViewModelService.cs b/src/Web/Grand.Web.Admin/Services/CollectionViewModelService.cs
index 87d207b0e..5c845e65e 100644
--- a/src/Web/Grand.Web.Admin/Services/CollectionViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/CollectionViewModelService.cs
@@ -33,7 +33,7 @@ public class CollectionViewModelService : ICollectionViewModelService
private readonly ITranslationService _translationService;
private readonly IDiscountService _discountService;
private readonly IVendorService _vendorService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ISeNameService _seNameService;
private readonly IEnumTranslationService _enumTranslationService;
@@ -51,7 +51,7 @@ public class CollectionViewModelService : ICollectionViewModelService
ITranslationService translationService,
IDiscountService discountService,
IVendorService vendorService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ISeNameService seNameService,
IEnumTranslationService enumTranslationService)
{
@@ -64,7 +64,7 @@ public class CollectionViewModelService : ICollectionViewModelService
_translationService = translationService;
_discountService = discountService;
_vendorService = vendorService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_seNameService = seNameService;
_enumTranslationService = enumTranslationService;
}
@@ -97,7 +97,7 @@ public class CollectionViewModelService : ICollectionViewModelService
ArgumentNullException.ThrowIfNull(model);
model.AvailableDiscounts = (await _discountService
- .GetDiscountsQuery(DiscountType.AssignedToCollections, _workContext.CurrentCustomer.Id))
+ .GetDiscountsQuery(DiscountType.AssignedToCollections, _workContextAccessor.WorkContext.CurrentCustomer.Id))
.Select(d => d.ToModel())
.ToList();
diff --git a/src/Web/Grand.Web.Admin/Services/ContactAttributeViewModelService.cs b/src/Web/Grand.Web.Admin/Services/ContactAttributeViewModelService.cs
index ffc036ea6..78fb57649 100644
--- a/src/Web/Grand.Web.Admin/Services/ContactAttributeViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/ContactAttributeViewModelService.cs
@@ -14,14 +14,14 @@ namespace Grand.Web.Admin.Services;
public class ContactAttributeViewModelService(
IContactAttributeService contactAttributeService,
IContactAttributeParser contactAttributeParser,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IEnumTranslationService enumTranslationService)
: IContactAttributeViewModelService
{
public virtual async Task<IEnumerable<ContactAttributeModel>> PrepareContactAttributeListModel()
{
var contactAttributes =
- await contactAttributeService.GetAllContactAttributes(workContext.CurrentCustomer.StaffStoreId, true);
+ await contactAttributeService.GetAllContactAttributes(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId, true);
return contactAttributes.Select(x =>
{
var attributeModel = x.ToModel();
@@ -49,7 +49,7 @@ public class ContactAttributeViewModelService(
EnableCondition = contactAttribute.ConditionAttribute.Any(),
SelectedAttributeId = selectedAttribute != null ? selectedAttribute.Id : "",
ConditionAttributes =
- (await contactAttributeService.GetAllContactAttributes(workContext.CurrentCustomer.StaffStoreId, true))
+ (await contactAttributeService.GetAllContactAttributes(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId, true))
//ignore this attribute and non-combinable attributes
.Where(x => x.Id != contactAttribute.Id && x.CanBeUsedAsCondition())
.Select(x =>
diff --git a/src/Web/Grand.Web.Admin/Services/ContactFormViewModelService.cs b/src/Web/Grand.Web.Admin/Services/ContactFormViewModelService.cs
index 29b68f3b0..8bf429298 100644
--- a/src/Web/Grand.Web.Admin/Services/ContactFormViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/ContactFormViewModelService.cs
@@ -19,19 +19,19 @@ public class ContactFormViewModelService : IContactFormViewModelService
private readonly IEmailAccountService _emailAccountService;
private readonly IStoreService _storeService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public ContactFormViewModelService(IContactUsService contactUsService,
IDateTimeService dateTimeService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IStoreService storeService,
IEmailAccountService emailAccountService)
{
_contactUsService = contactUsService;
_dateTimeService = dateTimeService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_storeService = storeService;
_emailAccountService = emailAccountService;
}
diff --git a/src/Web/Grand.Web.Admin/Services/CustomerReportViewModelService.cs b/src/Web/Grand.Web.Admin/Services/CustomerReportViewModelService.cs
index ead65a4f4..6ca916146 100644
--- a/src/Web/Grand.Web.Admin/Services/CustomerReportViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/CustomerReportViewModelService.cs
@@ -24,16 +24,16 @@ public class CustomerReportViewModelService : ICustomerReportViewModelService
private readonly IOrderStatusService _orderStatusService;
private readonly IPriceFormatter _priceFormatter;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IEnumTranslationService _enumTranslationService;
- public CustomerReportViewModelService(IWorkContext workContext,
+ public CustomerReportViewModelService(IWorkContextAccessor workContextAccessor,
ICustomerService customerService,
ITranslationService translationService, ICustomerReportService customerReportService,
IDateTimeService dateTimeService, IPriceFormatter priceFormatter,
IOrderStatusService orderStatusService, ICurrencyService currencyService, IEnumTranslationService enumTranslationService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_customerService = customerService;
_translationService = translationService;
_customerReportService = customerReportService;
diff --git a/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs b/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs
index deca9d07d..f2b40c6b1 100644
--- a/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs
@@ -69,7 +69,7 @@ public class CustomerViewModelService : ICustomerViewModelService
private readonly TaxSettings _taxSettings;
private readonly ITranslationService _translationService;
private readonly IVendorService _vendorService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IEnumTranslationService _enumTranslationService;
public CustomerViewModelService(
@@ -81,7 +81,7 @@ public class CustomerViewModelService : ICustomerViewModelService
ITranslationService translationService,
ILoyaltyPointsService loyaltyPointsService,
ICountryService countryService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IVendorService vendorService,
IStoreService storeService,
ICustomerAttributeParser customerAttributeParser,
@@ -115,7 +115,7 @@ public class CustomerViewModelService : ICustomerViewModelService
_customerSettings = customerSettings;
_commonSettings = commonSettings;
_enumTranslationService = enumTranslationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_vendorService = vendorService;
_addressSettings = addressSettings;
_storeService = storeService;
@@ -154,7 +154,7 @@ public class CustomerViewModelService : ICustomerViewModelService
CustomerListModel model,
string[] searchCustomerGroupIds, string[] searchCustomerTagIds, int pageIndex, int pageSize)
{
- var salesEmployeeId = _workContext.CurrentCustomer.SeId;
+ var salesEmployeeId = _workContextAccessor.WorkContext.CurrentCustomer.SeId;
var customers = await _customerService.GetAllCustomers(
customerGroupIds: searchCustomerGroupIds,
@@ -262,7 +262,7 @@ public class CustomerViewModelService : ICustomerViewModelService
}
else
{
- model.SeId = _workContext.CurrentCustomer.SeId;
+ model.SeId = _workContextAccessor.WorkContext.CurrentCustomer.SeId;
}
model.UsernamesEnabled = _customerSettings.UsernamesEnabled;
@@ -333,7 +333,7 @@ public class CustomerViewModelService : ICustomerViewModelService
model.LoyaltyPointsAvailableStores.Add(new SelectListItem {
Text = store.Shortcut,
Value = store.Id,
- Selected = store.Id == _workContext.CurrentStore.Id
+ Selected = store.Id == _workContextAccessor.WorkContext.CurrentStore.Id
});
//external authentication records
@@ -384,7 +384,7 @@ public class CustomerViewModelService : ICustomerViewModelService
IsTaxExempt = model.IsTaxExempt,
FreeShipping = model.FreeShipping,
Active = model.Active,
- StoreId = _workContext.CurrentStore.Id,
+ StoreId = _workContextAccessor.WorkContext.CurrentStore.Id,
OwnerId = ownerId,
Attributes = model.Attributes,
LastActivityDateUtc = DateTime.UtcNow
@@ -648,7 +648,7 @@ public class CustomerViewModelService : ICustomerViewModelService
{
var customers = new List<Customer>();
customers.AddRange(await _customerService.GetCustomersByIds(selectedIds.ToArray()));
- foreach (var customer in customers.Where(customer => customer.Id != _workContext.CurrentCustomer.Id))
+ foreach (var customer in customers.Where(customer => customer.Id != _workContextAccessor.WorkContext.CurrentCustomer.Id))
await _customerService.DeleteCustomer(customer);
}
@@ -731,7 +731,7 @@ public class CustomerViewModelService : ICustomerViewModelService
if (_addressSettings.CountryEnabled && !string.IsNullOrEmpty(model.CountryName))
addressHtmlSb.AppendFormat("{0}", WebUtility.HtmlEncode(model.CountryName));
var customAttributesFormatted =
- await _addressAttributeParser.FormatAttributes(_workContext.WorkingLanguage, x.Attributes);
+ await _addressAttributeParser.FormatAttributes(_workContextAccessor.WorkContext.WorkingLanguage, x.Attributes);
if (!string.IsNullOrEmpty(customAttributesFormatted))
//already encoded
addressHtmlSb.AppendFormat("<br />{0}", customAttributesFormatted);
@@ -1138,8 +1138,8 @@ public class CustomerViewModelService : ICustomerViewModelService
var messageProviderService = _httpContextAccessor.HttpContext!.RequestServices
.GetRequiredService<IMessageProviderService>();
await messageProviderService.SendNewCustomerNoteMessage(customerNote,
- await _customerService.GetCustomerById(customerId), _workContext.CurrentStore,
- _workContext.WorkingLanguage.Id);
+ await _customerService.GetCustomerById(customerId), _workContextAccessor.WorkContext.CurrentStore,
+ _workContextAccessor.WorkContext.WorkingLanguage.Id);
}
return customerNote;
diff --git a/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.cs b/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.cs
index 5f50406b6..e3bd7a93e 100644
--- a/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.cs
@@ -35,7 +35,7 @@ public class DiscountViewModelService : IDiscountViewModelService
ICurrencyService currencyService,
ICategoryService categoryService,
IProductService productService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ICollectionService collectionService,
IBrandService brandService,
IStoreService storeService,
@@ -52,7 +52,7 @@ public class DiscountViewModelService : IDiscountViewModelService
_currencyService = currencyService;
_categoryService = categoryService;
_productService = productService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_collectionService = collectionService;
_brandService = brandService;
_storeService = storeService;
@@ -74,7 +74,7 @@ public class DiscountViewModelService : IDiscountViewModelService
private readonly ICurrencyService _currencyService;
private readonly ICategoryService _categoryService;
private readonly IProductService _productService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IBrandService _brandService;
private readonly ICollectionService _collectionService;
private readonly IStoreService _storeService;
@@ -105,7 +105,7 @@ public class DiscountViewModelService : IDiscountViewModelService
if (model.SearchDiscountTypeId > 0)
discountType = (DiscountType)model.SearchDiscountTypeId;
var discounts = await _discountService.GetDiscountsQuery(discountType,
- _workContext.CurrentCustomer.StaffStoreId,
+ _workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId,
null,
model.SearchDiscountCouponCode,
model.SearchDiscountName);
@@ -251,7 +251,7 @@ public class DiscountViewModelService : IDiscountViewModelService
ArgumentNullException.ThrowIfNull(discountRequirementRule);
ArgumentNullException.ThrowIfNull(discount);
- var storeLocation = _workContext.CurrentHost.Url.TrimEnd('/');
+ var storeLocation = _workContextAccessor.WorkContext.CurrentHost.Url.TrimEnd('/');
var url =
$"{storeLocation}/{discountRequirementRule.GetConfigurationUrl(discount.Id, discountRequirementId)}";
diff --git a/src/Web/Grand.Web.Admin/Services/GiftVoucherViewModelService.cs b/src/Web/Grand.Web.Admin/Services/GiftVoucherViewModelService.cs
index 39d1b6f07..ee8f4a5db 100644
--- a/src/Web/Grand.Web.Admin/Services/GiftVoucherViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/GiftVoucherViewModelService.cs
@@ -26,7 +26,7 @@ public class GiftVoucherViewModelService : IGiftVoucherViewModelService
ICurrencyService currencyService,
LanguageSettings languageSettings,
ITranslationService translationService, ILanguageService languageService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IStoreService storeService)
{
_giftVoucherService = giftVoucherService;
diff --git a/src/Web/Grand.Web.Admin/Services/OrderViewModelService.cs b/src/Web/Grand.Web.Admin/Services/OrderViewModelService.cs
index 915ecd39a..8da41580a 100644
--- a/src/Web/Grand.Web.Admin/Services/OrderViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/OrderViewModelService.cs
@@ -48,7 +48,7 @@ public class OrderViewModelService : IOrderViewModelService
private readonly IPriceFormatter _priceFormatter;
private readonly IDiscountService _discountService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ICurrencyService _currencyService;
private readonly IPaymentService _paymentService;
private readonly IPaymentTransactionService _paymentTransactionService;
@@ -89,7 +89,7 @@ public class OrderViewModelService : IOrderViewModelService
IPriceFormatter priceFormatter,
IDiscountService discountService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ICurrencyService currencyService,
IPaymentService paymentService,
IPaymentTransactionService paymentTransactionService,
@@ -125,7 +125,7 @@ public class OrderViewModelService : IOrderViewModelService
_priceFormatter = priceFormatter;
_discountService = discountService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_currencyService = currencyService;
_paymentService = paymentService;
_paymentTransactionService = paymentTransactionService;
@@ -280,7 +280,7 @@ public class OrderViewModelService : IOrderViewModelService
if (product != null)
filterByProductId = model.ProductId;
- var salesEmployeeId = _workContext.CurrentCustomer.SeId;
+ var salesEmployeeId = _workContextAccessor.WorkContext.CurrentCustomer.SeId;
//load orders
var orders = await _orderService.SearchOrders(
@@ -591,7 +591,7 @@ public class OrderViewModelService : IOrderViewModelService
model.BillingAddress = await order.BillingAddress.ToModel(_countryService);
model.BillingAddress.FormattedCustomAddressAttributes =
- await _addressAttributeParser.FormatAttributes(_workContext.WorkingLanguage,
+ await _addressAttributeParser.FormatAttributes(_workContextAccessor.WorkContext.WorkingLanguage,
order.BillingAddress.Attributes);
model.BillingAddress.NameEnabled = _addressSettings.NameEnabled;
model.BillingAddress.FirstNameEnabled = true;
@@ -632,7 +632,7 @@ public class OrderViewModelService : IOrderViewModelService
{
model.ShippingAddress = await order.ShippingAddress.ToModel(_countryService);
model.ShippingAddress.FormattedCustomAddressAttributes =
- await _addressAttributeParser.FormatAttributes(_workContext.WorkingLanguage,
+ await _addressAttributeParser.FormatAttributes(_workContextAccessor.WorkContext.WorkingLanguage,
order.ShippingAddress.Attributes);
model.ShippingAddress.NameEnabled = _addressSettings.NameEnabled;
model.ShippingAddress.FirstNameEnabled = true;
@@ -1189,7 +1189,7 @@ public class OrderViewModelService : IOrderViewModelService
if (product != null)
filterByProductId = model.ProductId;
- var salesEmployeeId = _workContext.CurrentCustomer.SeId;
+ var salesEmployeeId = _workContextAccessor.WorkContext.CurrentCustomer.SeId;
//load orders
var orders = await _orderService.SearchOrders(model.StoreId,
diff --git a/src/Web/Grand.Web.Admin/Services/ProductViewModelService.cs b/src/Web/Grand.Web.Admin/Services/ProductViewModelService.cs
index 29570d0ca..83fd92a95 100644
--- a/src/Web/Grand.Web.Admin/Services/ProductViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/ProductViewModelService.cs
@@ -52,7 +52,7 @@ public class ProductViewModelService(
ITranslationService translationService,
IProductLayoutService productLayoutService,
ISpecificationAttributeService specificationAttributeService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
IWarehouseService warehouseService,
IDeliveryDateService deliveryDateService,
@@ -142,7 +142,7 @@ public class ProductViewModelService(
public virtual async Task PrepareTierPriceModel(ProductModel.TierPriceModel model)
{
- var storeId = workContext.CurrentCustomer.StaffStoreId;
+ var storeId = workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
if (string.IsNullOrEmpty(storeId))
model.AvailableStores.Add(new SelectListItem
@@ -404,7 +404,7 @@ public class ProductViewModelService(
//discounts
model.AvailableDiscounts = (await discountService
- .GetDiscountsQuery(DiscountType.AssignedToSkus, workContext.CurrentCustomer.StaffStoreId))
+ .GetDiscountsQuery(DiscountType.AssignedToSkus, workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
.Select(d => d.ToModel(dateTimeService))
.ToList();
if (!excludeProperties && product != null) model.SelectedDiscountIds = product.AppliedDiscounts.ToArray();
@@ -526,7 +526,7 @@ public class ProductViewModelService(
{
var model = new ProductListModel();
- var storeId = workContext.CurrentCustomer.StaffStoreId;
+ var storeId = workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
//stores
model.AvailableStores.Add(new SelectListItem
@@ -576,8 +576,8 @@ public class ProductViewModelService(
ProductListModel model, int pageIndex, int pageSize)
{
//limit for store manager
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
- model.SearchStoreId = workContext.CurrentCustomer.StaffStoreId;
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
+ model.SearchStoreId = workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var categoryIds = new List<string>();
if (!string.IsNullOrEmpty(model.SearchCategoryId))
@@ -651,7 +651,7 @@ public class ProductViewModelService(
public virtual async Task<IList<Product>> PrepareProducts(ProductListModel model)
{
//limit for store manager
- model.SearchStoreId = workContext.CurrentCustomer.StaffStoreId;
+ model.SearchStoreId = workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var categoryIds = new List<string>();
if (!string.IsNullOrEmpty(model.SearchCategoryId))
@@ -694,8 +694,8 @@ public class ProductViewModelService(
public virtual async Task<Product> InsertProductModel(ProductModel model)
{
//a staff should have access only to his products
- if (await groupService.IsStaff(workContext.CurrentCustomer))
- model.Stores = [workContext.CurrentCustomer.StaffStoreId];
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
//product
var product = model.ToEntity(dateTimeService);
@@ -703,7 +703,7 @@ public class ProductViewModelService(
//discounts
var allDiscounts =
await discountService.GetDiscountsQuery(DiscountType.AssignedToSkus,
- workContext.CurrentCustomer.StaffStoreId);
+ workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
foreach (var discount in allDiscounts)
if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))
{
@@ -734,8 +734,8 @@ public class ProductViewModelService(
public virtual async Task<Product> UpdateProductModel(Product product, ProductModel model)
{
//a staff should have access only to his products
- if (await groupService.IsStaff(workContext.CurrentCustomer))
- model.Stores = [workContext.CurrentCustomer.StaffStoreId];
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer))
+ model.Stores = [workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
var prevStockQuantity = stockQuantityService.GetTotalStockQuantity(product, total: true);
var prevMultiWarehouseStock = product.ProductWarehouseInventory.Select(i => new ProductWarehouseInventory
@@ -753,7 +753,7 @@ public class ProductViewModelService(
//discounts
var allDiscounts =
await discountService.GetDiscountsQuery(DiscountType.AssignedToSkus,
- workContext.CurrentCustomer.StaffStoreId);
+ workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
foreach (var discount in allDiscounts)
if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))
{
@@ -832,8 +832,8 @@ public class ProductViewModelService(
for (var i = 0; i < products.Count; i++)
{
var product = products[i];
- if (await groupService.IsStaff(workContext.CurrentCustomer))
- if (!(product.LimitedToStores && product.Stores.Contains(workContext.CurrentCustomer.StaffStoreId) &&
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer))
+ if (!(product.LimitedToStores && product.Stores.Contains(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
product.Stores.Count == 1))
continue;
await DeleteProduct(product);
@@ -850,7 +850,7 @@ public class ProductViewModelService(
ProductModel.AddProductModel model, int pageIndex, int pageSize)
{
//limit for store manager
- model.SearchStoreId = workContext.CurrentCustomer.StaffStoreId;
+ model.SearchStoreId = workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var products = await productService.PrepareProductList(model.SearchCategoryId, model.SearchBrandId,
model.SearchCollectionId, model.SearchStoreId, model.SearchVendorId, model.SearchProductTypeId,
@@ -1239,9 +1239,9 @@ public class ProductViewModelService(
new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = "0" });
// avaible stores
- if (await groupService.IsStaff(workContext.CurrentCustomer))
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer))
{
- storeId = workContext.CurrentCustomer.StaffStoreId;
+ storeId = workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var store = (await storeService.GetAllStores()).FirstOrDefault(x => x.Id == storeId);
if (store != null)
model.AvailableStores.Add(new SelectListItem { Text = store.Shortcut, Value = store.Id });
@@ -1262,8 +1262,8 @@ public class ProductViewModelService(
PrepareBulkEditProductModel(BulkEditListModel model, int pageIndex, int pageSize)
{
var storeId = model.SearchStoreId;
- if (await groupService.IsStaff(workContext.CurrentCustomer))
- storeId = workContext.CurrentCustomer.StaffStoreId;
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer))
+ storeId = workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var searchCategoryIds = new List<string>();
if (!string.IsNullOrEmpty(model.SearchCategoryId))
@@ -1305,8 +1305,8 @@ public class ProductViewModelService(
if (product != null)
{
//a staff can have access only to his products
- if (await groupService.IsStaff(workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
continue;
var prevStockQuantity = stockQuantityService.GetTotalStockQuantity(product, total: true);
@@ -1340,8 +1340,8 @@ public class ProductViewModelService(
var product = await productService.GetProductById(pModel.Id, true);
if (product != null)
{
- if (await groupService.IsStaff(workContext.CurrentCustomer))
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (await groupService.IsStaff(workContextAccessor.WorkContext.CurrentCustomer))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
continue;
await productService.DeleteProduct(product);
@@ -1351,7 +1351,7 @@ public class ProductViewModelService(
public virtual async Task<IList<ProductModel.TierPriceModel>> PrepareTierPriceModel(Product product)
{
- var storeId = workContext.CurrentCustomer.StaffStoreId;
+ var storeId = workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var items = new List<ProductModel.TierPriceModel>();
foreach (var x in product.TierPrices
@@ -1940,7 +1940,7 @@ public class ProductViewModelService(
foreach (var x in product.ProductAttributeCombinations)
{
var attributes = await productAttributeFormatter.FormatAttributes(product, x.Attributes,
- workContext.CurrentCustomer, "<br />", true, true, true, false, true, true);
+ workContextAccessor.WorkContext.CurrentCustomer, "<br />", true, true, true, false, true, true);
var pacModel = new ProductModel.ProductAttributeCombinationModel {
Id = x.Id,
ProductId = product.Id,
@@ -1991,7 +1991,7 @@ public class ProductViewModelService(
model.WarehouseInventoryModels = wim;
model.ProductId = product.Id;
model.Attributes = await productAttributeFormatter.FormatAttributes(product, combination.Attributes,
- workContext.CurrentCustomer, "<br />", true, true, true, false);
+ workContextAccessor.WorkContext.CurrentCustomer, "<br />", true, true, true, false);
if (model.UseMultipleWarehouses)
foreach (var _winv in combination.WarehouseInventory)
{
@@ -2610,7 +2610,7 @@ public class ProductViewModelService(
{
var model = new T();
- var storeId = workContext.CurrentCustomer.StaffStoreId;
+ var storeId = workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
//stores
model.AvailableStores.Add(new SelectListItem
diff --git a/src/Web/Grand.Web.Admin/Services/ShipmentViewModelService.cs b/src/Web/Grand.Web.Admin/Services/ShipmentViewModelService.cs
index ab2d15d20..91019e518 100644
--- a/src/Web/Grand.Web.Admin/Services/ShipmentViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/ShipmentViewModelService.cs
@@ -33,11 +33,11 @@ public class ShipmentViewModelService : IShipmentViewModelService
private readonly IStockQuantityService _stockQuantityService;
private readonly ITranslationService _translationService;
private readonly IWarehouseService _warehouseService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public ShipmentViewModelService(
IOrderService orderService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IProductService productService,
IShipmentService shipmentService,
IWarehouseService warehouseService,
@@ -53,7 +53,7 @@ public class ShipmentViewModelService : IShipmentViewModelService
ShippingProviderSettings shippingProviderSettings)
{
_orderService = orderService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_productService = productService;
_shipmentService = shipmentService;
_warehouseService = warehouseService;
@@ -163,7 +163,7 @@ public class ShipmentViewModelService : IShipmentViewModelService
await _countryService.GetCountryByTwoLetterIsoCode(shipmentEvent.CountryCode);
shipmentStatusEventModel.Country = shipmentEventCountry != null
? shipmentEventCountry.GetTranslation(x => x.Name,
- _workContext.WorkingLanguage.Id)
+ _workContextAccessor.WorkContext.WorkingLanguage.Id)
: shipmentEvent.CountryCode;
shipmentStatusEventModel.Date = shipmentEvent.Date;
shipmentStatusEventModel.EventName = shipmentEvent.EventName;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/AddAssociatedProductModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/AddAssociatedProductModelValidator.cs
index 0344071b0..0717dcc06 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/AddAssociatedProductModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/AddAssociatedProductModelValidator.cs
@@ -12,15 +12,15 @@ public class AddAssociatedProductModelValidator : BaseGrandValidator<ProductMode
{
public AddAssociatedProductModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.AddAssociatedProductModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/AddBundleProductModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/AddBundleProductModelValidator.cs
index ae0268ca7..621db2a69 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/AddBundleProductModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/AddBundleProductModelValidator.cs
@@ -12,15 +12,15 @@ public class AddBundleProductModelValidator : BaseGrandValidator<ProductModel.Ad
{
public AddBundleProductModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.AddBundleProductModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/AddCategoryProductModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/AddCategoryProductModelValidator.cs
index e5e77db45..7daa52fa4 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/AddCategoryProductModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/AddCategoryProductModelValidator.cs
@@ -12,15 +12,15 @@ public class AddCategoryProductModelValidator : BaseGrandValidator<CategoryModel
{
public AddCategoryProductModelValidator(
IEnumerable<IValidatorConsumer<CategoryModel.AddCategoryProductModel>> validators,
- ITranslationService translationService, ICategoryService categoryService, IWorkContext workContext)
+ ITranslationService translationService, ICategoryService categoryService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var category = await categoryService.GetCategoryById(x.CategoryId);
if (category != null)
- if (!category.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!category.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/AddCollectionProductModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/AddCollectionProductModelValidator.cs
index b6be48ac9..b6e005a86 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/AddCollectionProductModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/AddCollectionProductModelValidator.cs
@@ -12,15 +12,15 @@ public class AddCollectionProductModelValidator : BaseGrandValidator<CollectionM
{
public AddCollectionProductModelValidator(
IEnumerable<IValidatorConsumer<CollectionModel.AddCollectionProductModel>> validators,
- ITranslationService translationService, ICollectionService collectionService, IWorkContext workContext)
+ ITranslationService translationService, ICollectionService collectionService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var collection = await collectionService.GetCollectionById(x.CollectionId);
if (collection != null)
- if (!collection.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!collection.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/AddCrossSellProductModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/AddCrossSellProductModelValidator.cs
index a4c4f76b1..2dab4877b 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/AddCrossSellProductModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/AddCrossSellProductModelValidator.cs
@@ -12,15 +12,15 @@ public class AddCrossSellProductModelValidator : BaseGrandValidator<ProductModel
{
public AddCrossSellProductModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.AddCrossSellProductModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/AddProductSpecificationAttributeModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/AddProductSpecificationAttributeModelValidator.cs
index c4bf87b09..6b26ec7be 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/AddProductSpecificationAttributeModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/AddProductSpecificationAttributeModelValidator.cs
@@ -15,16 +15,16 @@ public class
{
public AddProductSpecificationAttributeModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.AddProductSpecificationAttributeModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext,
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor,
ISpecificationAttributeService specificationAttributeService)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/AddRelatedProductModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/AddRelatedProductModelValidator.cs
index 133b3fa35..4e6204fb5 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/AddRelatedProductModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/AddRelatedProductModelValidator.cs
@@ -12,15 +12,15 @@ public class AddRelatedProductModelValidator : BaseGrandValidator<ProductModel.A
{
public AddRelatedProductModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.AddRelatedProductModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/AddSimilarProductModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/AddSimilarProductModelValidator.cs
index be23ed582..c602fcf87 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/AddSimilarProductModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/AddSimilarProductModelValidator.cs
@@ -12,15 +12,15 @@ public class AddSimilarProductModelValidator : BaseGrandValidator<ProductModel.A
{
public AddSimilarProductModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.AddSimilarProductModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/AssociatedProductModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/AssociatedProductModelValidator.cs
index b26068502..cba14971c 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/AssociatedProductModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/AssociatedProductModelValidator.cs
@@ -12,15 +12,15 @@ public class AssociatedProductModelValidator : BaseGrandValidator<ProductModel.A
{
public AssociatedProductModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.AssociatedProductModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/BundleProductModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/BundleProductModelValidator.cs
index 296223753..c15665671 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/BundleProductModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/BundleProductModelValidator.cs
@@ -12,15 +12,15 @@ public class BundleProductModelValidator : BaseGrandValidator<ProductModel.Bundl
{
public BundleProductModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.BundleProductModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductBundleId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/CategoryProductModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/CategoryProductModelValidator.cs
index f4e850995..e8c992a00 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/CategoryProductModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/CategoryProductModelValidator.cs
@@ -12,15 +12,15 @@ public class CategoryProductModelValidator : BaseGrandValidator<CategoryModel.Ca
{
public CategoryProductModelValidator(
IEnumerable<IValidatorConsumer<CategoryModel.CategoryProductModel>> validators,
- ITranslationService translationService, ICategoryService categoryService, IWorkContext workContext)
+ ITranslationService translationService, ICategoryService categoryService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var category = await categoryService.GetCategoryById(x.CategoryId);
if (category != null)
- if (!category.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!category.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/CollectionProductModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/CollectionProductModelValidator.cs
index 928470049..ba7c67c8c 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/CollectionProductModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/CollectionProductModelValidator.cs
@@ -12,15 +12,15 @@ public class CollectionProductModelValidator : BaseGrandValidator<CollectionMode
{
public CollectionProductModelValidator(
IEnumerable<IValidatorConsumer<CollectionModel.CollectionProductModel>> validators,
- ITranslationService translationService, ICollectionService collectionService, IWorkContext workContext)
+ ITranslationService translationService, ICollectionService collectionService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var collection = await collectionService.GetCollectionById(x.CollectionId);
if (collection != null)
- if (!collection.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!collection.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/CrossSellProductModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/CrossSellProductModelValidator.cs
index 2448508e9..3d896c230 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/CrossSellProductModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/CrossSellProductModelValidator.cs
@@ -12,15 +12,15 @@ public class CrossSellProductModelValidator : BaseGrandValidator<ProductModel.Cr
{
public CrossSellProductModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.CrossSellProductModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/ProductAttributeMappingModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/ProductAttributeMappingModelValidator.cs
index 0c8068082..f93f26d4e 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/ProductAttributeMappingModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/ProductAttributeMappingModelValidator.cs
@@ -12,15 +12,15 @@ public class ProductAttributeMappingModelValidator : BaseGrandValidator<ProductM
{
public ProductAttributeMappingModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.ProductAttributeMappingModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/ProductAttributeValueModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/ProductAttributeValueModelValidator.cs
index 932ec20d7..fffe45682 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/ProductAttributeValueModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/ProductAttributeValueModelValidator.cs
@@ -13,7 +13,7 @@ public class ProductAttributeValueModelValidator : BaseGrandValidator<ProductMod
{
public ProductAttributeValueModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.ProductAttributeValueModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
RuleFor(x => x.Name)
@@ -28,12 +28,12 @@ public class ProductAttributeValueModelValidator : BaseGrandValidator<ProductMod
"Admin.Catalog.Products.ProductAttributes.Attributes.Values.Fields.Quantity.GreaterThanOrEqualTo1"))
.When(x => x.AttributeValueTypeId == AttributeValueType.AssociatedToProduct);
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/ProductCategoryModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/ProductCategoryModelValidator.cs
index 4310f88d0..44ae43e6e 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/ProductCategoryModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/ProductCategoryModelValidator.cs
@@ -12,15 +12,15 @@ public class ProductCategoryModelValidator : BaseGrandValidator<ProductModel.Pro
{
public ProductCategoryModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.ProductCategoryModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/ProductCollectionModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/ProductCollectionModelValidator.cs
index 081038f0d..9ee02b72f 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/ProductCollectionModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/ProductCollectionModelValidator.cs
@@ -12,15 +12,15 @@ public class ProductCollectionModelValidator : BaseGrandValidator<ProductModel.P
{
public ProductCollectionModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.ProductCollectionModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/ProductPictureModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/ProductPictureModelValidator.cs
index 9bdd77adc..bf3ff9342 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/ProductPictureModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/ProductPictureModelValidator.cs
@@ -12,15 +12,15 @@ public class ProductPictureModelValidator : BaseGrandValidator<ProductModel.Prod
{
public ProductPictureModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.ProductPictureModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/ProductSpecificationAttributeModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/ProductSpecificationAttributeModelValidator.cs
index 152bf0b7a..50892e588 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/ProductSpecificationAttributeModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/ProductSpecificationAttributeModelValidator.cs
@@ -12,15 +12,15 @@ public class ProductSpecificationAttributeModelValidator : BaseGrandValidator<Pr
{
public ProductSpecificationAttributeModelValidator(
IEnumerable<IValidatorConsumer<ProductSpecificationAttributeModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/RelatedProductModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/RelatedProductModelValidator.cs
index ef0267257..a39cdf3c7 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/RelatedProductModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/RelatedProductModelValidator.cs
@@ -12,15 +12,15 @@ public class RelatedProductModelValidator : BaseGrandValidator<ProductModel.Rela
{
public RelatedProductModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.RelatedProductModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId1);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/SimilarProductModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/SimilarProductModelValidator.cs
index 033c18970..b91a580b0 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/SimilarProductModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/SimilarProductModelValidator.cs
@@ -12,15 +12,15 @@ public class SimilarProductModelValidator : BaseGrandValidator<ProductModel.Simi
{
public SimilarProductModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.SimilarProductModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId1);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Catalog/TierPriceModelValidator.cs b/src/Web/Grand.Web.Admin/Validators/Catalog/TierPriceModelValidator.cs
index 88db1fbbc..7efd11096 100644
--- a/src/Web/Grand.Web.Admin/Validators/Catalog/TierPriceModelValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Catalog/TierPriceModelValidator.cs
@@ -12,15 +12,15 @@ public class TierPriceModelValidator : BaseGrandValidator<ProductModel.TierPrice
{
public TierPriceModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.TierPriceModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
@@ -32,15 +32,15 @@ public class TierPriceDeleteModelValidator : BaseGrandValidator<ProductModel.Tie
{
public TierPriceDeleteModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.TierPriceDeleteModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
- if (!string.IsNullOrEmpty(workContext.CurrentCustomer.StaffStoreId))
+ if (!string.IsNullOrEmpty(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product != null)
- if (!product.AccessToEntityByStore(workContext.CurrentCustomer.StaffStoreId))
+ if (!product.AccessToEntityByStore(workContextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return false;
return true;
diff --git a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs
index bcced77a7..4534f3633 100644
--- a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs
@@ -17,7 +17,7 @@ public class CustomerValidator : BaseGrandValidator<CustomerModel>
IEnumerable<IValidatorConsumer<CustomerModel>> validators,
ITranslationService translationService,
ICountryService countryService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ICustomerService customerService,
IGroupService groupService,
CustomerSettings customerSettings)
@@ -118,11 +118,11 @@ public class CustomerValidator : BaseGrandValidator<CustomerModel>
return "Add the customer to 'Guests' or 'Registered' customer group";
}
- if (await groupService.IsSalesManager(workContext.CurrentCustomer) &&
+ if (await groupService.IsSalesManager(workContextAccessor.WorkContext.CurrentCustomer) &&
(isInGuestsGroup || customerGroups.Count != 1))
return "Sales manager can assign role 'Registered' only";
- if (!await groupService.IsAdmin(workContext.CurrentCustomer) && isAdminGroup)
+ if (!await groupService.IsAdmin(workContextAccessor.WorkContext.CurrentCustomer) && isAdminGroup)
return "Only administrators can assign role 'Administrators'";
switch (isAdminGroup)
@@ -230,8 +230,8 @@ public class CustomerValidator : BaseGrandValidator<CustomerModel>
}
var customer = await customerService.GetCustomerById(x.Id);
- if (await groupService.IsSalesManager(workContext.CurrentCustomer) &&
- customer?.Id == workContext.CurrentCustomer.Id)
+ if (await groupService.IsSalesManager(workContextAccessor.WorkContext.CurrentCustomer) &&
+ customer?.Id == workContextAccessor.WorkContext.CurrentCustomer.Id)
context.AddFailure("You can't edit own data from admin panel");
if (customer != null && customer.Email != x.Email.ToLower())
diff --git a/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs b/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs
index 3e915e9e0..15eee301d 100644
--- a/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs
@@ -30,11 +30,11 @@ public class AffiliateAttribute : TypeFilterAttribute
public AffiliateFilter(IAffiliateService affiliateService,
ICustomerService customerService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_affiliateService = affiliateService;
_customerService = customerService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
#endregion
@@ -92,13 +92,13 @@ public class AffiliateAttribute : TypeFilterAttribute
if (affiliate is not { Active: true })
return;
- if (affiliate.Id == _workContext.CurrentCustomer.AffiliateId)
+ if (affiliate.Id == _workContextAccessor.WorkContext.CurrentCustomer.AffiliateId)
return;
//update affiliate identifier
- _workContext.CurrentCustomer.AffiliateId = affiliate.Id;
- await _customerService.UpdateCustomerField(_workContext.CurrentCustomer.Id, x => x.AffiliateId,
- _workContext.CurrentCustomer.AffiliateId);
+ _workContextAccessor.WorkContext.CurrentCustomer.AffiliateId = affiliate.Id;
+ await _customerService.UpdateCustomerField(_workContextAccessor.WorkContext.CurrentCustomer.Id, x => x.AffiliateId,
+ _workContextAccessor.WorkContext.CurrentCustomer.AffiliateId);
}
#endregion
@@ -114,7 +114,7 @@ public class AffiliateAttribute : TypeFilterAttribute
private readonly IAffiliateService _affiliateService;
private readonly ICustomerService _customerService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
#endregion
}
diff --git a/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.cs b/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.cs
index 27a1e572c..b022986b5 100644
--- a/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.cs
@@ -37,12 +37,12 @@ public class AuthorizeAdminAttribute : TypeFilterAttribute
#region Ctor
public AuthorizeAdminFilter(bool ignoreFilter, IPermissionService permissionService,
- SecuritySettings securitySettings, IWorkContext workContext, IGroupService groupService)
+ SecuritySettings securitySettings, IWorkContextAccessor workContextAccessor, IGroupService groupService)
{
_ignoreFilter = ignoreFilter;
_permissionService = permissionService;
_securitySettings = securitySettings;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
}
@@ -78,8 +78,8 @@ public class AuthorizeAdminAttribute : TypeFilterAttribute
filterContext.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());
//whether current customer is vendor
- if (await _groupService.IsVendor(_workContext.CurrentCustomer) ||
- _workContext.CurrentVendor is not null)
+ if (await _groupService.IsVendor(_workContextAccessor.WorkContext.CurrentCustomer) ||
+ _workContextAccessor.WorkContext.CurrentVendor is not null)
filterContext.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());
//get allowed IP addresses
@@ -102,7 +102,7 @@ public class AuthorizeAdminAttribute : TypeFilterAttribute
private readonly bool _ignoreFilter;
private readonly IPermissionService _permissionService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
private readonly SecuritySettings _securitySettings;
diff --git a/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs b/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs
index eb706be43..4bc964c8f 100644
--- a/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs
@@ -40,13 +40,13 @@ public class AuthorizeMenuAttribute : TypeFilterAttribute
bool ignoreFilter,
IPermissionService permissionService,
IAdminSiteMapService adminSiteMapService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
SecurityConfig securityConfig)
{
_ignoreFilter = ignoreFilter;
_permissionService = permissionService;
_adminSiteMapService = adminSiteMapService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_securityConfig = securityConfig;
}
@@ -57,7 +57,7 @@ public class AuthorizeMenuAttribute : TypeFilterAttribute
private readonly bool _ignoreFilter;
private readonly IPermissionService _permissionService;
private readonly IAdminSiteMapService _adminSiteMapService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly SecurityConfig _securityConfig;
#endregion
@@ -103,13 +103,13 @@ public class AuthorizeMenuAttribute : TypeFilterAttribute
if (menuSiteMap.AllPermissions)
{
if (!await menuSiteMap.PermissionNames.AllAsync(async x =>
- await _permissionService.Authorize(x, _workContext.CurrentCustomer)))
+ await _permissionService.Authorize(x, _workContextAccessor.WorkContext.CurrentCustomer)))
filterContext.Result = new ForbidResult();
}
else
{
if (!await menuSiteMap.PermissionNames.AnyAsync(async x =>
- await _permissionService.Authorize(x, _workContext.CurrentCustomer)))
+ await _permissionService.Authorize(x, _workContextAccessor.WorkContext.CurrentCustomer)))
filterContext.Result = new ForbidResult();
}
}
diff --git a/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.cs b/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.cs
index a1e3af9b1..b79c92a34 100644
--- a/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.cs
@@ -37,11 +37,11 @@ public class AuthorizeVendorAttribute : TypeFilterAttribute
{
#region Ctor
- public AuthorizeVendorFilter(bool ignoreFilter, IWorkContext workContext, IGroupService groupService,
+ public AuthorizeVendorFilter(bool ignoreFilter, IWorkContextAccessor workContextAccessor, IGroupService groupService,
IPermissionService permissionService)
{
_ignoreFilter = ignoreFilter;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_permissionService = permissionService;
}
@@ -76,7 +76,7 @@ public class AuthorizeVendorAttribute : TypeFilterAttribute
context.Result = new RedirectToRouteResult("VendorLogin", new RouteValueDictionary());
//ensure that this user has active vendor record associated
- if (!await _groupService.IsVendor(_workContext.CurrentCustomer) || _workContext.CurrentVendor == null)
+ if (!await _groupService.IsVendor(_workContextAccessor.WorkContext.CurrentCustomer) || _workContextAccessor.WorkContext.CurrentVendor == null)
context.Result = new RedirectToRouteResult("VendorLogin", new RouteValueDictionary());
}
@@ -86,7 +86,7 @@ public class AuthorizeVendorAttribute : TypeFilterAttribute
private readonly bool _ignoreFilter;
private readonly IPermissionService _permissionService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
#endregion
diff --git a/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.cs b/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.cs
index 18d9cc6e6..2240f0d64 100644
--- a/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.cs
@@ -39,13 +39,13 @@ public class ClosedStoreAttribute : TypeFilterAttribute
public CheckAccessClosedStoreFilter(bool ignoreFilter,
IPermissionService permissionService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IPageService pageService,
StoreInformationSettings storeInformationSettings)
{
_ignoreFilter = ignoreFilter;
_permissionService = permissionService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_pageService = pageService;
_storeInformationSettings = storeInformationSettings;
}
@@ -104,7 +104,7 @@ public class ClosedStoreAttribute : TypeFilterAttribute
{
//get identifiers of pages are accessible when a store is closed
var now = DateTime.UtcNow;
- var allowedPageIds = (await _pageService.GetAllPages(_workContext.CurrentStore.Id))
+ var allowedPageIds = (await _pageService.GetAllPages(_workContextAccessor.WorkContext.CurrentStore.Id))
.Where(t => t.AccessibleWhenStoreClosed &&
(!t.StartDateUtc.HasValue || t.StartDateUtc < now) &&
(!t.EndDateUtc.HasValue || t.EndDateUtc > now))
@@ -136,7 +136,7 @@ public class ClosedStoreAttribute : TypeFilterAttribute
private readonly bool _ignoreFilter;
private readonly IPermissionService _permissionService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IPageService _pageService;
private readonly StoreInformationSettings _storeInformationSettings;
diff --git a/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.cs b/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.cs
index 9e682858e..5db6f14a7 100644
--- a/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.cs
@@ -32,11 +32,11 @@ public class CustomerActivityAttribute : TypeFilterAttribute
public CustomerActivityFilter(
ICustomerService customerService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
CustomerSettings customerSettings)
{
_customerService = customerService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_customerSettings = customerSettings;
}
@@ -65,8 +65,8 @@ public class CustomerActivityAttribute : TypeFilterAttribute
return;
//update last activity date
- if (_workContext.CurrentCustomer.LastActivityDateUtc.AddMinutes(3.0) < DateTime.UtcNow)
- await _customerService.UpdateCustomerField(_workContext.CurrentCustomer, x => x.LastActivityDateUtc,
+ if (_workContextAccessor.WorkContext.CurrentCustomer.LastActivityDateUtc.AddMinutes(3.0) < DateTime.UtcNow)
+ await _customerService.UpdateCustomerField(_workContextAccessor.WorkContext.CurrentCustomer, x => x.LastActivityDateUtc,
DateTime.UtcNow);
//get current IP address
@@ -74,11 +74,11 @@ public class CustomerActivityAttribute : TypeFilterAttribute
//update customer's IP address
if (!string.IsNullOrEmpty(currentIpAddress) &&
- !currentIpAddress.Equals(_workContext.CurrentCustomer.LastIpAddress,
+ !currentIpAddress.Equals(_workContextAccessor.WorkContext.CurrentCustomer.LastIpAddress,
StringComparison.OrdinalIgnoreCase))
{
- _workContext.CurrentCustomer.LastIpAddress = currentIpAddress;
- await _customerService.UpdateCustomerField(_workContext.CurrentCustomer, x => x.LastIpAddress,
+ _workContextAccessor.WorkContext.CurrentCustomer.LastIpAddress = currentIpAddress;
+ await _customerService.UpdateCustomerField(_workContextAccessor.WorkContext.CurrentCustomer, x => x.LastIpAddress,
currentIpAddress);
}
@@ -88,10 +88,10 @@ public class CustomerActivityAttribute : TypeFilterAttribute
return;
//save new one if don't match
- if (!pageUrl.Equals(_workContext.CurrentCustomer.LastVisitedPage, StringComparison.OrdinalIgnoreCase))
+ if (!pageUrl.Equals(_workContextAccessor.WorkContext.CurrentCustomer.LastVisitedPage, StringComparison.OrdinalIgnoreCase))
{
- _workContext.CurrentCustomer.LastVisitedPage = pageUrl;
- await _customerService.UpdateCustomerField(_workContext.CurrentCustomer, x => x.LastVisitedPage, pageUrl);
+ _workContextAccessor.WorkContext.CurrentCustomer.LastVisitedPage = pageUrl;
+ await _customerService.UpdateCustomerField(_workContextAccessor.WorkContext.CurrentCustomer, x => x.LastVisitedPage, pageUrl);
}
}
@@ -100,7 +100,7 @@ public class CustomerActivityAttribute : TypeFilterAttribute
#region Fields
private readonly ICustomerService _customerService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly CustomerSettings _customerSettings;
#endregion
diff --git a/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.cs b/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.cs
index 491a6b547..4c2ef74a2 100644
--- a/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.cs
@@ -33,10 +33,10 @@ public class DenySystemAccountAttribute : TypeFilterAttribute
{
#region Ctor
- public DenySystemAccountFilter(bool ignoreFilter, IWorkContext workContext)
+ public DenySystemAccountFilter(bool ignoreFilter, IWorkContextAccessor workContextAccessor)
{
_ignoreFilter = ignoreFilter;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
#endregion
@@ -63,7 +63,7 @@ public class DenySystemAccountAttribute : TypeFilterAttribute
if (!DataSettingsManager.DatabaseIsInstalled())
return Task.CompletedTask;
- if (_workContext.CurrentCustomer.IsSystemAccount())
+ if (_workContextAccessor.WorkContext.CurrentCustomer.IsSystemAccount())
context.Result = new RedirectToRouteResult("HomePage", new RouteValueDictionary());
return Task.CompletedTask;
@@ -74,7 +74,7 @@ public class DenySystemAccountAttribute : TypeFilterAttribute
#region Fields
private readonly bool _ignoreFilter;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
#endregion
}
diff --git a/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs b/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs
index 0138f3be7..158b06258 100644
--- a/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs
@@ -34,10 +34,10 @@ public class LanguageAttribute : TypeFilterAttribute
#region Ctor
public LanguageSeoCodeFilter(
- IWorkContext workContext, ILanguageService languageService,
+ IWorkContextAccessor workContextAccessor, ILanguageService languageService,
AppConfig config)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_languageService = languageService;
_config = config;
}
@@ -46,7 +46,7 @@ public class LanguageAttribute : TypeFilterAttribute
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ILanguageService _languageService;
private readonly AppConfig _config;
@@ -96,7 +96,7 @@ public class LanguageAttribute : TypeFilterAttribute
return;
}
- pageUrl = AddLanguageSeo(pageUrl, _workContext.WorkingLanguage);
+ pageUrl = AddLanguageSeo(pageUrl, _workContextAccessor.WorkContext.WorkingLanguage);
context.Result = new RedirectResult(pageUrl, false);
}
diff --git a/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.cs b/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.cs
index 777ad3b4b..276cb27f3 100644
--- a/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.cs
@@ -30,9 +30,9 @@ public class PasswordExpiredAttribute : TypeFilterAttribute
{
#region Ctor
- public PasswordFilter(IWorkContext workContext, IMediator mediator)
+ public PasswordFilter(IWorkContextAccessor workContextAccessor, IMediator mediator)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
}
@@ -67,7 +67,7 @@ public class PasswordExpiredAttribute : TypeFilterAttribute
{
//check password expiration
var passwordIsExpired = await _mediator.Send(new GetPasswordIsExpiredQuery
- { Customer = _workContext.CurrentCustomer });
+ { Customer = _workContextAccessor.WorkContext.CurrentCustomer });
if (passwordIsExpired)
//redirect to ChangePassword page if expires
context.Result = new RedirectToRouteResult("CustomerChangePassword", new RouteValueDictionary());
@@ -78,7 +78,7 @@ public class PasswordExpiredAttribute : TypeFilterAttribute
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
#endregion
diff --git a/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs b/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs
index 01517ebca..13e07696c 100644
--- a/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs
+++ b/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs
@@ -106,9 +106,8 @@ public class BackgroundServiceTask : BackgroundService
private async Task WorkContext(IServiceProvider serviceProvider, ScheduleTask scheduleTask)
{
+ var workContextAccessor = serviceProvider.GetRequiredService<IWorkContextAccessor>();
var workContext = serviceProvider.GetRequiredService<IWorkContextSetter>();
- var storeHelper = serviceProvider.GetRequiredService<IStoreHelper>();
- await workContext.SetCurrentCustomer();
- await storeHelper.SetCurrentStore(scheduleTask.StoreId);
+ workContextAccessor.WorkContext = await workContext.InitializeWorkContext(scheduleTask.StoreId);
}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs b/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs
index f5fc5049d..84adf8d81 100644
--- a/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs
+++ b/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs
@@ -255,7 +255,7 @@ public static class ServiceCollectionExtensions
var type = item.GetType();
var storeId = "";
var settingService = x.GetRequiredService<ISettingService>();
- var store = x.GetRequiredService<IStoreHelper>().StoreHost;
+ var store = x.GetRequiredService<IWorkContextAccessor>().WorkContext?.CurrentStore;
if (store != null)
storeId = store.Id;
diff --git a/src/Web/Grand.Web.Common/Localization/IEnumTranslationService.cs b/src/Web/Grand.Web.Common/Localization/IEnumTranslationService.cs
index 5a3da4827..630e8064b 100644
--- a/src/Web/Grand.Web.Common/Localization/IEnumTranslationService.cs
+++ b/src/Web/Grand.Web.Common/Localization/IEnumTranslationService.cs
@@ -12,7 +12,7 @@ public interface IEnumTranslationService
string GetTranslationEnum<T>(T enumValue) where T : struct;
}
-public class EnumTranslationService(ITranslationService translationService, IWorkContext workContext) : IEnumTranslationService
+public class EnumTranslationService(ITranslationService translationService, IWorkContextAccessor workContextAccessor) : IEnumTranslationService
{
public SelectList ToSelectList<TEnum>(TEnum enumObj, bool markCurrentAsSelected = true, int[] valuesToExclude = null)
where TEnum : struct
@@ -41,7 +41,7 @@ public class EnumTranslationService(ITranslationService translationService, IWor
//Translation value
var resourceName = $"Enums.{typeof(T)}.{enumValue.ToString()}";
- var result = translationService.GetResource(resourceName, workContext.WorkingLanguage.Id, "", true);
+ var result = translationService.GetResource(resourceName, workContextAccessor.WorkContext.WorkingLanguage.Id, "", true);
//set default value if required
if (string.IsNullOrEmpty(result))
diff --git a/src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.cs
index 46b86870c..02fb3bbcb 100644
--- a/src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.cs
+++ b/src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.cs
@@ -1,7 +1,6 @@
using Grand.Infrastructure;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
namespace Grand.Web.Common.Middleware;
@@ -18,10 +17,9 @@ public class ContextLoggingMiddleware
_next = next;
}
- public async Task InvokeAsync(HttpContext context)
+ public async Task InvokeAsync(HttpContext context, IWorkContextAccessor workContextAccessor)
{
- var workContext = context.RequestServices.GetRequiredService<IWorkContext>();
-
+ var workContext = workContextAccessor.WorkContext;
var requestTelemetry = context.Features.Get<RequestTelemetry>();
if (requestTelemetry != null)
{
diff --git a/src/Web/Grand.Web.Common/Middleware/CultureSettingMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/CultureSettingMiddleware.cs
index 25f2c6b18..dcf461186 100644
--- a/src/Web/Grand.Web.Common/Middleware/CultureSettingMiddleware.cs
+++ b/src/Web/Grand.Web.Common/Middleware/CultureSettingMiddleware.cs
@@ -13,11 +13,11 @@ public class CultureSettingMiddleware
_next = next;
}
- public async Task InvokeAsync(HttpContext context, IWorkContext workContext)
+ public async Task InvokeAsync(HttpContext context, IWorkContextAccessor workContextAccessor)
{
- if (workContext.WorkingLanguage != null)
+ if (workContextAccessor.WorkContext.WorkingLanguage != null)
{
- var culture = new CultureInfo(workContext.WorkingLanguage.LanguageCulture);
+ var culture = new CultureInfo(workContextAccessor.WorkContext.WorkingLanguage.LanguageCulture);
CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;
diff --git a/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs
index 7e956ff65..2ea239085 100644
--- a/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs
+++ b/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs
@@ -32,16 +32,13 @@ public class WorkContextMiddleware
/// <param name="context">HTTP context</param>
/// <param name="workContext">workContext</param>
/// <returns>Task</returns>
- public async Task InvokeAsync(HttpContext context, IWorkContextSetter workContext)
+ public async Task InvokeAsync(HttpContext context, IWorkContextSetter workContextSetter, IWorkContextAccessor workContextAccessor)
{
if (context?.Request == null) return;
//set current context
- var customer = await workContext.SetCurrentCustomer();
- await workContext.SetCurrentVendor(customer);
- _ = await workContext.SetWorkingLanguage(customer);
- await workContext.SetWorkingCurrency(customer);
- await workContext.SetTaxDisplayType(customer);
+ var workContext = await workContextSetter.InitializeWorkContext();
+ workContextAccessor.WorkContext = workContext;
//call the next middleware in the request pipeline
await _next(context);
diff --git a/src/Web/Grand.Web.Common/Security/Authorization/CustomerGroupAuthorizeAttribute.cs b/src/Web/Grand.Web.Common/Security/Authorization/CustomerGroupAuthorizeAttribute.cs
index 5079a022d..8cb68eb40 100644
--- a/src/Web/Grand.Web.Common/Security/Authorization/CustomerGroupAuthorizeAttribute.cs
+++ b/src/Web/Grand.Web.Common/Security/Authorization/CustomerGroupAuthorizeAttribute.cs
@@ -24,7 +24,7 @@ public class CustomerGroupAuthorizeAttribute : Attribute, IAsyncAuthorizationFil
return;
var groupService = context.HttpContext.RequestServices.GetRequiredService<IGroupService>();
- var workContext = context.HttpContext.RequestServices.GetRequiredService<IWorkContext>();
+ var workContext = context.HttpContext.RequestServices.GetRequiredService<IWorkContextAccessor>().WorkContext;
if (await groupService.IsInCustomerGroup(workContext.CurrentCustomer, GroupName))
return;
diff --git a/src/Web/Grand.Web.Common/Startup/StartupApplication.cs b/src/Web/Grand.Web.Common/Startup/StartupApplication.cs
index 61643d14d..6a1611c08 100644
--- a/src/Web/Grand.Web.Common/Startup/StartupApplication.cs
+++ b/src/Web/Grand.Web.Common/Startup/StartupApplication.cs
@@ -79,11 +79,8 @@ public class StartupApplication : IStartupApplication
private void RegisterContextService(IServiceCollection serviceCollection)
{
//work context
- serviceCollection.AddScoped<IWorkContext, WorkContext>();
- serviceCollection.AddScoped<IWorkContextSetter>(provider => provider.GetService<IWorkContext>() as WorkContext);
-
- //helper for Settings
- serviceCollection.AddScoped<IStoreHelper, StoreHelper>();
+ serviceCollection.AddSingleton<IWorkContextAccessor, WorkContextAccessor>();
+ serviceCollection.AddScoped<IWorkContextSetter, WorkContextSetter>();
//View factory
serviceCollection.AddScoped<IViewFactory, ViewFactory>();
diff --git a/src/Web/Grand.Web.Common/StoreHelper.cs b/src/Web/Grand.Web.Common/StoreHelper.cs
deleted file mode 100644
index f0b2ff39b..000000000
--- a/src/Web/Grand.Web.Common/StoreHelper.cs
+++ /dev/null
@@ -1,148 +0,0 @@
-using Grand.Business.Core.Interfaces.Common.Stores;
-using Grand.Domain.Stores;
-using Grand.Infrastructure;
-using Grand.Infrastructure.Configuration;
-using Microsoft.AspNetCore.Http;
-
-namespace Grand.Web.Common;
-
-public class StoreHelper : IStoreHelper
-{
- #region Ctor
-
- public StoreHelper(
- IHttpContextAccessor httpContextAccessor,
- IStoreService storeService,
- SecurityConfig securityConfig)
- {
- _httpContextAccessor = httpContextAccessor;
- _storeService = storeService;
- _securityConfig = securityConfig;
- }
-
- #endregion
-
- public Store StoreHost {
- get {
- if (_cachedStore != null) return _cachedStore;
- //try to determine the current store by HOST header
- var host = _httpContextAccessor.HttpContext?.Request.Host.Host;
-
- var allStores = _storeService.GetAll();
- var stores = allStores.Where(s => s.ContainsHostValue(host)).ToList();
- if (!stores.Any())
- _cachedStore = allStores.FirstOrDefault();
- else
- switch (stores.Count)
- {
- case 1:
- _cachedStore = stores.FirstOrDefault();
- break;
- case > 1:
- {
- var cookie = GetStoreCookie();
- if (!string.IsNullOrEmpty(cookie))
- {
- var storeCookie = stores.FirstOrDefault(x => x.Id == cookie);
- _cachedStore = storeCookie ?? stores.FirstOrDefault();
- }
- else
- {
- _cachedStore = stores.FirstOrDefault();
- }
-
- break;
- }
- }
-
- return _cachedStore ?? throw new Exception("No store could be loaded");
- }
- }
-
- public DomainHost DomainHost {
- get {
- if (_cachedDomainHost != null) return _cachedDomainHost;
- //try to determine the current HOST header
- var host = _httpContextAccessor.HttpContext?.Request.GetTypedHeaders().Host.ToString();
- if (StoreHost != null)
- _cachedDomainHost = StoreHost.HostValue(host) ?? new DomainHost {
- Id = int.MinValue.ToString(),
- Url = StoreHost.SslEnabled ? StoreHost.SecureUrl : StoreHost.Url,
- HostName = "temporary-store"
- };
-
- return _cachedDomainHost ??= new DomainHost {
- Id = int.MinValue.ToString(),
- Url = host,
- HostName = "temporary"
- };
- }
- }
-
- /// <summary>
- /// Set the current store by BackgroundService
- /// </summary>
- /// <returns></returns>
- public virtual async Task<Store> SetCurrentStore(string storeId)
- {
- if (!string.IsNullOrEmpty(storeId))
- {
- var store = await _storeService.GetStoreById(storeId);
- if (store != null)
- _cachedStore = store;
- }
-
- _cachedStore ??= (await _storeService.GetAllStores()).FirstOrDefault();
-
- return _cachedStore ?? throw new Exception("No store could be loaded by BackgroundService");
- }
-
- /// <summary>
- /// Set store cookie
- /// </summary>
- /// <param name="storeId">Store ident</param>
- public virtual async Task SetStoreCookie(string storeId)
- {
- if (_httpContextAccessor.HttpContext == null)
- return;
-
- var store = await _storeService.GetStoreById(storeId);
- if (store == null)
- return;
-
- //remove current cookie
- _httpContextAccessor.HttpContext.Response.Cookies.Delete(StoreCookieName);
-
- //get date of cookie expiration
- var cookieExpiresDate = DateTime.UtcNow.AddHours(_securityConfig.CookieAuthExpires);
-
- //set new cookie value
- var options = new CookieOptions {
- HttpOnly = true,
- Expires = cookieExpiresDate
- };
- _httpContextAccessor.HttpContext.Response.Cookies.Append(StoreCookieName, storeId, options);
- }
-
-
- #region Utilities
-
- protected virtual string GetStoreCookie()
- {
- return _httpContextAccessor.HttpContext?.Request.Cookies[StoreCookieName];
- }
-
- #endregion
-
- #region Fields
-
- private readonly IHttpContextAccessor _httpContextAccessor;
- private readonly IStoreService _storeService;
- private readonly SecurityConfig _securityConfig;
- private Store _cachedStore;
- private DomainHost _cachedDomainHost;
-
- private const string StoreCookieName = ".Grand.Store";
-
- #endregion
-}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminLabelTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminLabelTagHelper.cs
index 812063394..d858d12c6 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminLabelTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminLabelTagHelper.cs
@@ -14,12 +14,12 @@ public class LabelRequiredTagHelper : LabelTagHelper
private const string RequiredAttributeName = "asp-required";
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public LabelRequiredTagHelper(IHtmlGenerator generator, IWorkContext workContext,
+ public LabelRequiredTagHelper(IHtmlGenerator generator, IWorkContextAccessor workContextAccessor,
ITranslationService translationService) : base(generator)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_translationService = translationService;
}
@@ -42,7 +42,7 @@ public class LabelRequiredTagHelper : LabelTagHelper
var resourceDisplayName = For.Metadata.GetDisplayName();
- var langId = _workContext.WorkingLanguage.Id;
+ var langId = _workContextAccessor.WorkContext.WorkingLanguage.Id;
var resource = _translationService.GetResource(
resourceDisplayName.ToLowerInvariant(), langId, returnEmptyIfNotFound: true);
diff --git a/src/Web/Grand.Web.Common/TagHelpers/HtmlTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/HtmlTagHelper.cs
index 26842f3ea..86a72ff2f 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/HtmlTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/HtmlTagHelper.cs
@@ -10,11 +10,11 @@ public class HtmlTagHelper : TagHelper
private const string ForAttributeName = "use-lang";
private readonly IPageHeadBuilder _pageHeadBuilder;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public HtmlTagHelper(IWorkContext workContext, IPageHeadBuilder pageHeadBuilder)
+ public HtmlTagHelper(IWorkContextAccessor workContextAccessor, IPageHeadBuilder pageHeadBuilder)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_pageHeadBuilder = pageHeadBuilder;
}
@@ -24,8 +24,8 @@ public class HtmlTagHelper : TagHelper
{
if (UseLanguage)
{
- output.Attributes.Add("lang", _workContext.WorkingLanguage.UniqueSeoCode);
- if (_workContext.WorkingLanguage.Rtl)
+ output.Attributes.Add("lang", _workContextAccessor.WorkContext.WorkingLanguage.UniqueSeoCode);
+ if (_workContextAccessor.WorkContext.WorkingLanguage.Rtl)
output.Attributes.Add("dir", "rtl");
}
diff --git a/src/Web/Grand.Web.Common/WorkContextAccessor.cs b/src/Web/Grand.Web.Common/WorkContextAccessor.cs
new file mode 100644
index 000000000..68bad61c4
--- /dev/null
+++ b/src/Web/Grand.Web.Common/WorkContextAccessor.cs
@@ -0,0 +1,13 @@
+using Grand.Infrastructure;
+
+namespace Grand.Web.Common;
+
+public class WorkContextAccessor : IWorkContextAccessor
+{
+ private static readonly AsyncLocal<IWorkContext> _asyncLocalWorkContext = new();
+
+ public IWorkContext WorkContext {
+ get => _asyncLocalWorkContext.Value;
+ set => _asyncLocalWorkContext.Value = value;
+ }
+}
diff --git a/src/Web/Grand.Web.Common/WorkContext.cs b/src/Web/Grand.Web.Common/WorkContextSetter.cs
similarity index 61%
rename from src/Web/Grand.Web.Common/WorkContext.cs
rename to src/Web/Grand.Web.Common/WorkContextSetter.cs
index 80e35d7ef..97256e0a1 100644
--- a/src/Web/Grand.Web.Common/WorkContext.cs
+++ b/src/Web/Grand.Web.Common/WorkContextSetter.cs
@@ -2,6 +2,7 @@
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Domain.Common;
using Grand.Domain.Customers;
@@ -12,6 +13,7 @@ using Grand.Domain.Tax;
using Grand.Domain.Vendors;
using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
+using Grand.SharedKernel.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
@@ -23,21 +25,20 @@ namespace Grand.Web.Common;
/// <summary>
/// Represents work context for web application / current customer / store / language / currency
/// </summary>
-public class WorkContext : IWorkContext, IWorkContextSetter
+public class WorkContextSetter : IWorkContextSetter
{
#region Ctor
- public WorkContext(
+ public WorkContextSetter(
IHttpContextAccessor httpContextAccessor,
IGrandAuthenticationService authenticationService,
ICurrencyService currencyService,
ICustomerService customerService,
IGroupService groupService,
ILanguageService languageService,
- IStoreHelper storeHelper,
+ IStoreService storeService,
IAclService aclService,
IVendorService vendorService,
- LanguageSettings languageSettings,
TaxSettings taxSettings,
AppConfig config)
{
@@ -47,10 +48,9 @@ public class WorkContext : IWorkContext, IWorkContextSetter
_customerService = customerService;
_groupService = groupService;
_languageService = languageService;
- _storeHelper = storeHelper;
+ _storeService = storeService;
_aclService = aclService;
_vendorService = vendorService;
- _languageSettings = languageSettings;
_taxSettings = taxSettings;
_config = config;
}
@@ -65,21 +65,14 @@ public class WorkContext : IWorkContext, IWorkContextSetter
private readonly ICustomerService _customerService;
private readonly IGroupService _groupService;
private readonly ILanguageService _languageService;
- private readonly IStoreHelper _storeHelper;
+ private readonly IStoreService _storeService;
private readonly IAclService _aclService;
private readonly IVendorService _vendorService;
- private readonly LanguageSettings _languageSettings;
private readonly TaxSettings _taxSettings;
private readonly AppConfig _config;
- private Customer _cachedCustomer;
private Customer _originalCustomerIfImpersonated;
- private Vendor _cachedVendor;
- private Language _cachedLanguage;
- private Currency _cachedCurrency;
-
- private TaxDisplayType _cachedTaxDisplayType;
#endregion
@@ -89,7 +82,7 @@ public class WorkContext : IWorkContext, IWorkContextSetter
/// Get language from the requested page URL
/// </summary>
/// <returns>The found language</returns>
- protected virtual async Task<Language> GetLanguageFromUrl(IList<Language> languages)
+ protected virtual async Task<Language> GetLanguageFromUrl(IList<Language> languages, Store store)
{
if (_httpContextAccessor.HttpContext?.Request == null)
return await Task.FromResult<Language>(null);
@@ -98,15 +91,15 @@ public class WorkContext : IWorkContext, IWorkContextSetter
if (string.IsNullOrEmpty(path))
return await Task.FromResult<Language>(null);
- var firstSegment = path.Split(['/'], StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ??
- string.Empty;
+ var firstSegment = path.Split(['/'], StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? string.Empty;
+
if (string.IsNullOrEmpty(firstSegment))
return await Task.FromResult<Language>(null);
var language = languages.FirstOrDefault(urlLanguage =>
urlLanguage.UniqueSeoCode.Equals(firstSegment, StringComparison.OrdinalIgnoreCase));
- if (language is not { Published: true } || !_aclService.Authorize(language, CurrentStore.Id))
+ if (language is not { Published: true } || !_aclService.Authorize(language, store.Id))
return await Task.FromResult<Language>(null);
return language;
@@ -116,7 +109,7 @@ public class WorkContext : IWorkContext, IWorkContextSetter
/// Get language from the request
/// </summary>
/// <returns>The found language</returns>
- protected virtual async Task<Language> GetLanguageFromRequest(IList<Language> languages)
+ protected virtual async Task<Language> GetLanguageFromRequest(IList<Language> languages, Store store)
{
if (_httpContextAccessor.HttpContext?.Request == null)
return await Task.FromResult<Language>(null);
@@ -133,63 +126,74 @@ public class WorkContext : IWorkContext, IWorkContextSetter
//check language availability
if (requestLanguage is not { Published: true } ||
- !_aclService.Authorize(requestLanguage, CurrentStore.Id))
+ !_aclService.Authorize(requestLanguage, store.Id))
return await Task.FromResult<Language>(null);
return requestLanguage;
}
- protected virtual async Task<Customer> SetImpersonatedCustomer(Customer customer)
+ protected virtual async Task<Customer> OriginalCustomerIfImpersonated(Customer customer)
{
- //get impersonate user if required
- var impersonatedCustomerId =
- customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.ImpersonatedCustomerId);
+ var impersonatedCustomerId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.ImpersonatedCustomerId);
if (string.IsNullOrEmpty(impersonatedCustomerId)) return null;
var impersonatedCustomer = await _customerService.GetCustomerById(impersonatedCustomerId);
if (impersonatedCustomer is not { Deleted: false, Active: true }) return null;
- //set impersonated customer
- _originalCustomerIfImpersonated = customer;
return impersonatedCustomer;
}
+
#endregion
#region Properties
- /// <summary>
- /// Gets the current customer
- /// </summary>
- public virtual Customer CurrentCustomer => _cachedCustomer;
+ public virtual async Task<IWorkContext> InitializeWorkContext(string storeId = null)
+ {
+ var currentStore = await CurrentStore(storeId);
+ var workContext = new CurrentWorkContext {
+ CurrentStore = currentStore,
+ CurrentHost = CurrentHost(currentStore),
+ CurrentCustomer = await CurrentCustomer(currentStore)
+ };
+
+ if (workContext.CurrentCustomer != null)
+ {
+ workContext.CurrentVendor = await CurrentVendor(workContext.CurrentCustomer);
+ workContext.OriginalCustomerIfImpersonated = _originalCustomerIfImpersonated;
+ workContext.WorkingLanguage = await WorkingLanguage(workContext.CurrentCustomer, workContext.CurrentStore);
+ workContext.WorkingCurrency = await WorkingCurrency(workContext.CurrentCustomer, workContext.WorkingLanguage, workContext.CurrentStore);
+ workContext.TaxDisplayType = await TaxDisplayType(workContext.CurrentCustomer, workContext.CurrentStore);
+ }
+ return workContext;
+ }
/// <summary>
/// Set the current customer by Middleware
/// </summary>
/// <returns></returns>
- public virtual async Task<Customer> SetCurrentCustomer()
+ protected async Task<Customer> CurrentCustomer(Store store)
{
var customer = await GetBackgroundTaskCustomer();
- if (customer != null) return _cachedCustomer = customer;
+ if (customer != null) return customer;
customer = await GetAuthenticatedCustomer();
- if (customer != null) return _cachedCustomer = customer;
+ if (customer != null) return customer;
customer = await GetGuestCustomer();
- if (customer != null) return _cachedCustomer = customer;
+ if (customer != null) return customer;
customer = await GetApiUserCustomer();
- if (customer != null) return _cachedCustomer = customer;
+ if (customer != null) return customer;
customer = await GetSearchEngineCustomer();
- if (customer != null) return _cachedCustomer = customer;
+ if (customer != null) return customer;
customer = await GetAllowAnonymousCustomer();
- if (customer != null) return _cachedCustomer = customer;
+ if (customer != null) return customer;
//create guest if not exists
- customer = await CreateCustomerGuest();
+ customer = await CreateCustomerGuest(store);
- //cache the found customer
- return _cachedCustomer = customer;
+ return customer;
}
private async Task<Customer> GetBackgroundTaskCustomer()
@@ -212,10 +216,12 @@ public class WorkContext : IWorkContext, IWorkContextSetter
var customer = await _authenticationService.GetAuthenticatedCustomer();
if (customer == null) return null;
- var impersonatedCustomer = await SetImpersonatedCustomer(customer);
+ var impersonatedCustomer = await ImpersonatedCustomer(customer);
if (impersonatedCustomer != null)
- customer = impersonatedCustomer;
-
+ {
+ _originalCustomerIfImpersonated = customer;
+ return impersonatedCustomer;
+ }
return customer;
}
@@ -247,26 +253,28 @@ public class WorkContext : IWorkContext, IWorkContextSetter
return null;
}
- private async Task<Customer> CreateCustomerGuest()
+ private async Task<Customer> CreateCustomerGuest(Store store)
{
var userFields = new List<UserField>();
- if (!string.IsNullOrEmpty(CurrentStore.DefaultCurrencyId))
+ if (!string.IsNullOrEmpty(store.DefaultCurrencyId))
userFields.Add(new UserField {
- Key = SystemCustomerFieldNames.CurrencyId, Value = CurrentStore.DefaultCurrencyId,
- StoreId = CurrentStore.Id
+ Key = SystemCustomerFieldNames.CurrencyId,
+ Value = store.DefaultCurrencyId,
+ StoreId = store.Id
});
- if (!string.IsNullOrEmpty(CurrentStore.DefaultLanguageId))
+ if (!string.IsNullOrEmpty(store.DefaultLanguageId))
userFields.Add(new UserField {
- Key = SystemCustomerFieldNames.LanguageId, Value = CurrentStore.DefaultLanguageId,
- StoreId = CurrentStore.Id
+ Key = SystemCustomerFieldNames.LanguageId,
+ Value = store.DefaultLanguageId,
+ StoreId = store.Id
});
var customer = new Customer {
CustomerGuid = Guid.NewGuid(),
Active = true,
- StoreId = CurrentStore.Id,
+ StoreId = store.Id,
LastActivityDateUtc = DateTime.UtcNow,
LastIpAddress = _httpContextAccessor?.HttpContext?.Connection?.RemoteIpAddress?.ToString(),
UserFields = userFields
@@ -280,32 +288,22 @@ public class WorkContext : IWorkContext, IWorkContextSetter
}
/// <summary>
- /// Set the current customer
+ /// Get Impersonated customer
/// </summary>
- /// <returns></returns>
- public virtual async Task<Customer> SetCurrentCustomer(Customer customer)
+ protected async Task<Customer> ImpersonatedCustomer(Customer customer)
{
- if (customer == null || customer.Deleted || !customer.Active)
- //if the current customer is null/not active then set background task customer
- customer = await _customerService.GetCustomerBySystemName(SystemCustomerNames.BackgroundTask);
-
- return _cachedCustomer = customer ?? throw new Exception("No customer could be loaded");
+ var impersonatedCustomerId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.ImpersonatedCustomerId);
+ if (string.IsNullOrEmpty(impersonatedCustomerId)) return null;
+ var impersonatedCustomer = await _customerService.GetCustomerById(impersonatedCustomerId);
+ if (impersonatedCustomer is not { Deleted: false, Active: true }) return null;
+ return impersonatedCustomer;
}
- /// <summary>
- /// Gets the original customer
- /// </summary>
- public virtual Customer OriginalCustomerIfImpersonated => _originalCustomerIfImpersonated;
-
- /// <summary>
- /// Gets the current vendor
- /// </summary>
- public virtual Vendor CurrentVendor => _cachedVendor;
/// <summary>
/// Set the current vendor (logged-in manager)
/// </summary>
- public virtual async Task<Vendor> SetCurrentVendor(Customer customer)
+ protected async Task<Vendor> CurrentVendor(Customer customer)
{
if (customer == null)
return await Task.FromResult<Vendor>(null);
@@ -321,20 +319,15 @@ public class WorkContext : IWorkContext, IWorkContextSetter
return await Task.FromResult<Vendor>(null);
//cache the found vendor
- return _cachedVendor = vendor;
+ return vendor;
}
- /// <summary>
- /// Gets or sets current user working language
- /// </summary>
- public virtual Language WorkingLanguage => _cachedLanguage;
-
/// <summary>
/// Set current user working language by Middleware
/// </summary>
/// <param name="customer"></param>
/// <returns></returns>
- public virtual async Task<Language> SetWorkingLanguage(Customer customer)
+ protected async Task<Language> WorkingLanguage(Customer customer, Store store)
{
Language language = null;
@@ -343,18 +336,17 @@ public class WorkContext : IWorkContext, IWorkContextSetter
var allStoreLanguages = await _languageService.GetAllLanguages(adminAreaUrl ?? false);
if (allStoreLanguages.Count == 1)
- return _cachedLanguage = allStoreLanguages.FirstOrDefault();
+ return allStoreLanguages.FirstOrDefault();
if (_config.SeoFriendlyUrlsForLanguagesEnabled)
- language = await GetLanguageFromUrl(allStoreLanguages);
+ language = await GetLanguageFromUrl(allStoreLanguages, store);
//get current lang identifier
var customerLanguageId =
- customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId, CurrentStore.Id);
+ customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId, store.Id);
- if (_languageSettings.AutomaticallyDetectLanguage &&
- language == null && string.IsNullOrEmpty(customerLanguageId))
- language = await GetLanguageFromRequest(allStoreLanguages);
+ if (language == null && string.IsNullOrEmpty(customerLanguageId))
+ language = await GetLanguageFromRequest(allStoreLanguages, store);
//check customer language
var customerLanguage = (language ??
@@ -362,21 +354,17 @@ public class WorkContext : IWorkContext, IWorkContextSetter
? allStoreLanguages.FirstOrDefault(lang => lang.Id == customerLanguageId)
: allStoreLanguages.FirstOrDefault(lang =>
//if the language for the current store not exist, then use the first
- lang.Id == CurrentStore.DefaultLanguageId))) ??
+ lang.Id == store.DefaultLanguageId))) ??
allStoreLanguages.FirstOrDefault();
- return _cachedLanguage = customerLanguage ?? throw new Exception("No language could be loaded");
+ return customerLanguage ?? throw new Exception("No language could be loaded");
}
- /// <summary>
- /// Get current user working currency
- /// </summary>
- public virtual Currency WorkingCurrency => _cachedCurrency;
/// <summary>
/// Set current user working currency by Middleware
/// </summary>
- public virtual async Task<Currency> SetWorkingCurrency(Customer customer)
+ protected async Task<Currency> WorkingCurrency(Customer customer, Language language, Store store)
{
//return store currency when we're you are in admin panel
var adminAreaUrl =
@@ -386,44 +374,38 @@ public class WorkContext : IWorkContext, IWorkContextSetter
var primaryStoreCurrency = await _currencyService.GetPrimaryStoreCurrency();
if (primaryStoreCurrency != null)
{
- _cachedCurrency = primaryStoreCurrency;
return primaryStoreCurrency;
}
}
- var allStoreCurrencies = await _currencyService.GetAllCurrencies(storeId: CurrentStore?.Id);
+ var allStoreCurrencies = await _currencyService.GetAllCurrencies(storeId: store.Id);
if (allStoreCurrencies.Count == 1)
- return _cachedCurrency = allStoreCurrencies.FirstOrDefault();
+ return allStoreCurrencies.FirstOrDefault();
var customerCurrencyId =
- customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CurrencyId, CurrentStore?.Id);
+ customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CurrencyId, store.Id);
var customerCurrency = (allStoreCurrencies.FirstOrDefault(currency => currency.Id == customerCurrencyId) ??
- (!string.IsNullOrEmpty(CurrentStore?.DefaultCurrencyId)
+ (!string.IsNullOrEmpty(store.DefaultCurrencyId)
? allStoreCurrencies.FirstOrDefault(currency =>
- currency.Id == CurrentStore.DefaultCurrencyId)
+ currency.Id == store.DefaultCurrencyId)
: allStoreCurrencies.FirstOrDefault(currency =>
- currency.Id == WorkingLanguage.DefaultCurrencyId))) ??
+ currency.Id == language.DefaultCurrencyId))) ??
allStoreCurrencies.FirstOrDefault();
- return _cachedCurrency = customerCurrency ?? throw new Exception("No currency could be loaded");
+ return customerCurrency ?? throw new Exception("No currency could be loaded");
}
- /// <summary>
- /// Gets or sets current tax display type
- /// </summary>
- public virtual TaxDisplayType TaxDisplayType => _cachedTaxDisplayType;
-
- public virtual async Task<TaxDisplayType> SetTaxDisplayType(Customer customer)
+ protected async Task<TaxDisplayType> TaxDisplayType(Customer customer, Store store)
{
TaxDisplayType taxDisplayType;
if (_taxSettings.AllowCustomersToSelectTaxDisplayType && customer != null)
{
var taxDisplayTypeId =
- customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.TaxDisplayTypeId, CurrentStore.Id);
+ customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.TaxDisplayTypeId, store.Id);
taxDisplayType = (TaxDisplayType)taxDisplayTypeId;
}
else
@@ -432,21 +414,86 @@ public class WorkContext : IWorkContext, IWorkContextSetter
taxDisplayType = _taxSettings.TaxDisplayType;
}
- //cache the value
- _cachedTaxDisplayType = taxDisplayType;
+ return await Task.FromResult(taxDisplayType);
+ }
- return await Task.FromResult(_cachedTaxDisplayType);
+ private string GetStoreCookie()
+ {
+ return _httpContextAccessor.HttpContext?.Request.Cookies[CommonHelper.StoreCookieName];
}
- /// <summary>
- /// Gets the current store
- /// </summary>
- public virtual Store CurrentStore => _storeHelper.StoreHost;
+ protected async Task<Store> CurrentStore(string id = null)
+ {
+ if (!string.IsNullOrEmpty(id))
+ return await _storeService.GetStoreById(id);
+
+ var host = _httpContextAccessor.HttpContext?.Request.Host.Host;
+
+ var allStores = await _storeService.GetAllStores();
+ var stores = allStores.Where(s => s.ContainsHostValue(host)).ToList();
+ if (!stores.Any())
+ return allStores.FirstOrDefault();
+ else
+ switch (stores.Count)
+ {
+ case 1:
+ return stores.FirstOrDefault();
+ case > 1:
+ {
+ var cookie = GetStoreCookie();
+ if (!string.IsNullOrEmpty(cookie))
+ {
+ var storeCookie = stores.FirstOrDefault(x => x.Id == cookie);
+ return storeCookie ?? stores.FirstOrDefault();
+ }
+ else
+ {
+ return stores.FirstOrDefault();
+ }
+ }
+ }
+
+ throw new Exception("No store could be loaded");
+ }
/// <summary>
/// Gets the current domain host
/// </summary>
- public virtual DomainHost CurrentHost => _storeHelper.DomainHost;
+ protected DomainHost CurrentHost(Store store)
+ {
+ //try to determine the current HOST header
+ var host = _httpContextAccessor.HttpContext?.Request.GetTypedHeaders().Host.ToString();
+ if (store != null)
+ return store.HostValue(host) ?? new DomainHost {
+ Id = int.MinValue.ToString(),
+ Url = store.SslEnabled ? store.SecureUrl : store.Url,
+ HostName = "temporary-store"
+ };
+
+ return new DomainHost {
+ Id = int.MinValue.ToString(),
+ Url = host,
+ HostName = "temporary"
+ };
+ }
+
+ private class CurrentWorkContext : IWorkContext
+ {
+ public Customer CurrentCustomer { get; set; }
+
+ public Customer OriginalCustomerIfImpersonated { get; set; }
+
+ public Vendor CurrentVendor { get; set; }
+
+ public Language WorkingLanguage { get; set; }
+
+ public Currency WorkingCurrency { get; set; }
+
+ public TaxDisplayType TaxDisplayType { get; set; }
+
+ public Store CurrentStore { get; set; }
+ public DomainHost CurrentHost { get; set; }
+ }
#endregion
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Home/Index.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Home/Index.cshtml
index a3794c564..e4925855a 100644
--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Home/Index.cshtml
+++ b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Home/Index.cshtml
@@ -1,4 +1,4 @@
-@inject IWorkContext WorkContext;
+@inject IWorkContextAccessor workContextAccessor;
@{
//page title
ViewBag.Title = Loc["Vendor.Dashboard"];
@@ -9,7 +9,7 @@
<div class="col-md-12">
<div class="x_panel">
<div class="x_title">
- <h2>@Loc["Vendor.Dashboard.Summary"] - @WorkContext.CurrentVendor.Name</h2>
+ <h2>@Loc["Vendor.Dashboard.Summary"] - @workContextAccessor.WorkContext.CurrentVendor.Name</h2>
<div class="filter">
<div class="page-bar" style="height:43px;">
<div class="page-toolbar">
diff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/PdfTemplates/ShipmentPdfTemplate.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/PdfTemplates/ShipmentPdfTemplate.cshtml
index 899c29b45..30ff7550d 100644
--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/PdfTemplates/ShipmentPdfTemplate.cshtml
+++ b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/PdfTemplates/ShipmentPdfTemplate.cshtml
@@ -6,12 +6,12 @@
@inject IOrderService _orderService
@inject IProductService _productService
@inject ICountryService _countryService
-@inject IWorkContext _workContext
+@inject IWorkContextAccessor _workContextAccessor
@inject ITranslationService _translationService
@{
- var companyName = _workContext.CurrentStore.CompanyName;
- var limitbyVendor = _workContext.CurrentVendor != null;
+ var companyName = _workContextAccessor.WorkContext.CurrentStore.CompanyName;
+ var limitbyVendor = _workContextAccessor.WorkContext.CurrentVendor != null;
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
@@ -118,7 +118,7 @@
@foreach (var item in shipment.ShipmentItems)
{
var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == item.OrderItemId);
- if (orderItem != null && (orderItem.VendorId == _workContext.CurrentVendor?.Id || !limitbyVendor))
+ if (orderItem != null && (orderItem.VendorId == _workContextAccessor.WorkContext.CurrentVendor?.Id || !limitbyVendor))
{
<tr>
<td colspan="2">
diff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/Partials/HeadVendor.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/Partials/HeadVendor.cshtml
index 1dcb462c5..8fe69c0a7 100644
--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/Partials/HeadVendor.cshtml
+++ b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/Partials/HeadVendor.cshtml
@@ -1,12 +1,12 @@
@using Grand.Domain.Localization
@using Constants = Grand.SharedUIResources.Constants
@inject LanguageSettings languageSettings
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
<script>
const wwwrootpath = '@(Constants.WwwRoot)';
</script>
@{
- var supportRtl = workContext.WorkingLanguage.Rtl &&
+ var supportRtl = workContextAccessor.WorkContext.WorkingLanguage.Rtl &&
!languageSettings.IgnoreRtlPropertyForAdminArea;
var kendoVersion = "2021.3.914";
diff --git a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/_VendorLayout.cshtml b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/_VendorLayout.cshtml
index fe8892bd2..b22fd9e83 100644
--- a/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/_VendorLayout.cshtml
+++ b/src/Web/Grand.Web.Vendor/Areas/Vendor/Views/Shared/_VendorLayout.cshtml
@@ -4,13 +4,13 @@
@using Grand.Web.Vendor.Components
@using Microsoft.AspNetCore.Mvc.TagHelpers
@using Constants = Grand.SharedUIResources.Constants
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@inject LanguageSettings languageSettings
@inject VendorSettings vendorSettings
@{
- var currentCustomer = workContext.CurrentCustomer;
+ var currentCustomer = workContextAccessor.WorkContext.CurrentCustomer;
var currentVersion = GrandVersion.FullVersion;
- var supportRtl = workContext.WorkingLanguage.Rtl &&
+ var supportRtl = workContextAccessor.WorkContext.WorkingLanguage.Rtl &&
!languageSettings.IgnoreRtlPropertyForAdminArea;
//page title
diff --git a/src/Web/Grand.Web.Vendor/Components/VendorWidget.cs b/src/Web/Grand.Web.Vendor/Components/VendorWidget.cs
index 3c183bc04..ef2e9fb71 100644
--- a/src/Web/Grand.Web.Vendor/Components/VendorWidget.cs
+++ b/src/Web/Grand.Web.Vendor/Components/VendorWidget.cs
@@ -10,10 +10,10 @@ public class VendorWidgetViewComponent : BaseVendorViewComponent
{
#region Constructors
- public VendorWidgetViewComponent(IWidgetService widgetService, IWorkContext workContext)
+ public VendorWidgetViewComponent(IWidgetService widgetService, IWorkContextAccessor workContextAccessor)
{
_widgetService = widgetService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
#endregion
@@ -24,8 +24,8 @@ public class VendorWidgetViewComponent : BaseVendorViewComponent
{
var model = new List<VendorWidgetModel>();
- var widgets = await _widgetService.LoadActiveWidgetsByWidgetZone(widgetZone, _workContext.CurrentStore.Id,
- _workContext.CurrentCustomer);
+ var widgets = await _widgetService.LoadActiveWidgetsByWidgetZone(widgetZone, _workContextAccessor.WorkContext.CurrentStore.Id,
+ _workContextAccessor.WorkContext.CurrentCustomer);
foreach (var item in widgets)
{
var viewComponentName = await item.GetPublicViewComponentName(widgetZone);
@@ -51,7 +51,7 @@ public class VendorWidgetViewComponent : BaseVendorViewComponent
#region Fields
private readonly IWidgetService _widgetService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
#endregion
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Vendor/Controllers/HomeController.cs b/src/Web/Grand.Web.Vendor/Controllers/HomeController.cs
index c7b64590f..b27f74ea5 100644
--- a/src/Web/Grand.Web.Vendor/Controllers/HomeController.cs
+++ b/src/Web/Grand.Web.Vendor/Controllers/HomeController.cs
@@ -13,11 +13,11 @@ public class HomeController : BaseVendorController
#region Ctor
public HomeController(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ILogger<HomeController> logger,
IGrandAuthenticationService authenticationService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_logger = logger;
_authenticationService = authenticationService;
}
@@ -26,7 +26,7 @@ public class HomeController : BaseVendorController
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ILogger<HomeController> _logger;
private readonly IGrandAuthenticationService _authenticationService;
@@ -46,7 +46,7 @@ public class HomeController : BaseVendorController
public IActionResult AccessDenied()
{
- _logger.LogInformation("Access denied to user #{CurrentCustomerEmail}", _workContext.CurrentCustomer.Email);
+ _logger.LogInformation("Access denied to user #{CurrentCustomerEmail}", _workContextAccessor.WorkContext.CurrentCustomer.Email);
return View();
}
diff --git a/src/Web/Grand.Web.Vendor/Controllers/LoginController.cs b/src/Web/Grand.Web.Vendor/Controllers/LoginController.cs
index 7a27ad27c..08a040689 100644
--- a/src/Web/Grand.Web.Vendor/Controllers/LoginController.cs
+++ b/src/Web/Grand.Web.Vendor/Controllers/LoginController.cs
@@ -28,7 +28,7 @@ public class LoginController : BaseController
private readonly IMediator _mediator;
private readonly IMessageProviderService _messageProviderService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public LoginController(
CustomerSettings customerSettings,
@@ -38,7 +38,7 @@ public class LoginController : BaseController
ICustomerService customerService,
IGrandAuthenticationService authenticationService,
IMessageProviderService messageProviderService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator)
{
_customerSettings = customerSettings;
@@ -48,7 +48,7 @@ public class LoginController : BaseController
_customerService = customerService;
_authenticationService = authenticationService;
_messageProviderService = messageProviderService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
}
@@ -128,11 +128,11 @@ public class LoginController : BaseController
if (_customerSettings.TwoFactorAuthenticationType != TwoFactorAuthenticationType.AppVerification)
{
- await twoFactorAuthenticationService.GenerateCodeSetup("", customer, _workContext.WorkingLanguage,
+ await twoFactorAuthenticationService.GenerateCodeSetup("", customer, _workContextAccessor.WorkContext.WorkingLanguage,
_customerSettings.TwoFactorAuthenticationType);
if (_customerSettings.TwoFactorAuthenticationType == TwoFactorAuthenticationType.EmailVerification)
await _messageProviderService.SendCustomerEmailTokenValidationMessage(customer,
- _workContext.CurrentStore, _workContext.WorkingLanguage.Id);
+ _workContextAccessor.WorkContext.CurrentStore, _workContextAccessor.WorkContext.WorkingLanguage.Id);
}
return View();
diff --git a/src/Web/Grand.Web.Vendor/Controllers/MerchandiseReturnController.cs b/src/Web/Grand.Web.Vendor/Controllers/MerchandiseReturnController.cs
index d808969d9..5a2fa0784 100644
--- a/src/Web/Grand.Web.Vendor/Controllers/MerchandiseReturnController.cs
+++ b/src/Web/Grand.Web.Vendor/Controllers/MerchandiseReturnController.cs
@@ -24,12 +24,12 @@ public class MerchandiseReturnController : BaseVendorController
IMerchandiseReturnViewModelService merchandiseReturnViewModelService,
ITranslationService translationService,
IMerchandiseReturnService merchandiseReturnService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_merchandiseReturnViewModelService = merchandiseReturnViewModelService;
_translationService = translationService;
_merchandiseReturnService = merchandiseReturnService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
#endregion
@@ -39,7 +39,7 @@ public class MerchandiseReturnController : BaseVendorController
private readonly IMerchandiseReturnViewModelService _merchandiseReturnViewModelService;
private readonly ITranslationService _translationService;
private readonly IMerchandiseReturnService _merchandiseReturnService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
#endregion Fields
@@ -77,7 +77,7 @@ public class MerchandiseReturnController : BaseVendorController
public async Task<IActionResult> GoToId(MerchandiseReturnListModel model)
{
var merchandiseReturn = await _merchandiseReturnService.GetMerchandiseReturnById(model.GoDirectlyToId);
- if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContext.CurrentVendor.Id)
+ if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
//not found
return RedirectToAction("List", "MerchandiseReturn");
@@ -89,7 +89,7 @@ public class MerchandiseReturnController : BaseVendorController
public async Task<IActionResult> ProductsForMerchandiseReturn(string merchandiseReturnId)
{
var merchandiseReturn = await _merchandiseReturnService.GetMerchandiseReturnById(merchandiseReturnId);
- if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContext.CurrentVendor.Id)
+ if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
return ErrorForKendoGridJson("Merchandise return not found");
var items = await _merchandiseReturnViewModelService.PrepareMerchandiseReturnItemModel(merchandiseReturnId);
@@ -106,7 +106,7 @@ public class MerchandiseReturnController : BaseVendorController
public async Task<IActionResult> Edit(string id)
{
var merchandiseReturn = await _merchandiseReturnService.GetMerchandiseReturnById(id);
- if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContext.CurrentVendor.Id)
+ if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
//No merchandise return found with the specified id
return RedirectToAction("List");
@@ -125,7 +125,7 @@ public class MerchandiseReturnController : BaseVendorController
)
{
var merchandiseReturn = await _merchandiseReturnService.GetMerchandiseReturnById(model.Id);
- if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContext.CurrentVendor.Id)
+ if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
//No merchandise return found with the specified id
return RedirectToAction("List");
@@ -157,7 +157,7 @@ public class MerchandiseReturnController : BaseVendorController
public async Task<IActionResult> Delete(string id)
{
var merchandiseReturn = await _merchandiseReturnService.GetMerchandiseReturnById(id);
- if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContext.CurrentVendor.Id)
+ if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
//No merchandise return found with the specified id
return RedirectToAction("List");
@@ -181,7 +181,7 @@ public class MerchandiseReturnController : BaseVendorController
public async Task<IActionResult> MerchandiseReturnNotesSelect(string merchandiseReturnId)
{
var merchandiseReturn = await _merchandiseReturnService.GetMerchandiseReturnById(merchandiseReturnId);
- if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContext.CurrentVendor.Id)
+ if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No merchandise return found with the specified id");
//merchandise return notes
@@ -199,7 +199,7 @@ public class MerchandiseReturnController : BaseVendorController
string message)
{
var merchandiseReturn = await _merchandiseReturnService.GetMerchandiseReturnById(merchandiseReturnId);
- if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContext.CurrentVendor.Id)
+ if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
return Json(new { Result = false });
await _merchandiseReturnViewModelService.InsertMerchandiseReturnNote(merchandiseReturn, displayToCustomer,
@@ -213,7 +213,7 @@ public class MerchandiseReturnController : BaseVendorController
public async Task<IActionResult> MerchandiseReturnNoteDelete(string id, string merchandiseReturnId)
{
var merchandiseReturn = await _merchandiseReturnService.GetMerchandiseReturnById(merchandiseReturnId);
- if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContext.CurrentVendor.Id)
+ if (merchandiseReturn == null || merchandiseReturn.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No merchandise return found with the specified id");
await _merchandiseReturnViewModelService.DeleteMerchandiseReturnNote(merchandiseReturn, id);
diff --git a/src/Web/Grand.Web.Vendor/Controllers/OrderController.cs b/src/Web/Grand.Web.Vendor/Controllers/OrderController.cs
index 2ffffc30f..f1293a516 100644
--- a/src/Web/Grand.Web.Vendor/Controllers/OrderController.cs
+++ b/src/Web/Grand.Web.Vendor/Controllers/OrderController.cs
@@ -23,13 +23,13 @@ public class OrderController : BaseVendorController
IOrderViewModelService orderViewModelService,
IOrderService orderService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IPdfService pdfService)
{
_orderViewModelService = orderViewModelService;
_orderService = orderService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_pdfService = pdfService;
}
@@ -40,7 +40,7 @@ public class OrderController : BaseVendorController
private readonly IOrderViewModelService _orderViewModelService;
private readonly IOrderService _orderService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IPdfService _pdfService;
#endregion
@@ -71,7 +71,7 @@ public class OrderController : BaseVendorController
//products
const int productNumber = 15;
var products = (await productService.SearchProducts(
- vendorId: _workContext.CurrentVendor.Id,
+ vendorId: _workContextAccessor.WorkContext.CurrentVendor.Id,
keywords: term,
pageSize: productNumber,
showHidden: true)).products;
@@ -133,7 +133,7 @@ public class OrderController : BaseVendorController
public async Task<IActionResult> Edit(string id)
{
var order = await _orderService.GetOrderById(id);
- if (order == null || order.Deleted || !_workContext.HasAccessToOrder(order))
+ if (order == null || order.Deleted || !_workContextAccessor.WorkContext.HasAccessToOrder(order))
//No order found with the specified id
return RedirectToAction("List");
@@ -147,7 +147,7 @@ public class OrderController : BaseVendorController
{
var order = await _orderService.GetOrderById(orderId);
//No order found with the specified id
- if (order == null || order.Deleted || !_workContext.HasAccessToOrder(order)) return RedirectToAction("List");
+ if (order == null || order.Deleted || !_workContextAccessor.WorkContext.HasAccessToOrder(order)) return RedirectToAction("List");
var orders = new List<Order> {
order
@@ -155,8 +155,8 @@ public class OrderController : BaseVendorController
byte[] bytes;
using (var stream = new MemoryStream())
{
- await _pdfService.PrintOrdersToPdf(stream, orders, _workContext.WorkingLanguage.Id,
- _workContext.CurrentVendor.Id);
+ await _pdfService.PrintOrdersToPdf(stream, orders, _workContextAccessor.WorkContext.WorkingLanguage.Id,
+ _workContextAccessor.WorkContext.CurrentVendor.Id);
bytes = stream.ToArray();
}
@@ -172,8 +172,8 @@ public class OrderController : BaseVendorController
byte[] bytes;
using (var stream = new MemoryStream())
{
- await _pdfService.PrintOrdersToPdf(stream, orders, _workContext.WorkingLanguage.Id,
- _workContext.CurrentVendor.Id);
+ await _pdfService.PrintOrdersToPdf(stream, orders, _workContextAccessor.WorkContext.WorkingLanguage.Id,
+ _workContextAccessor.WorkContext.CurrentVendor.Id);
bytes = stream.ToArray();
}
@@ -195,7 +195,7 @@ public class OrderController : BaseVendorController
}
//a vendor should have access only to his products
- orders = orders.Where(_workContext.HasAccessToOrder).ToList();
+ orders = orders.Where(_workContextAccessor.WorkContext.HasAccessToOrder).ToList();
//ensure that we at least one order selected
if (orders.Count == 0)
@@ -207,8 +207,8 @@ public class OrderController : BaseVendorController
byte[] bytes;
using (var stream = new MemoryStream())
{
- await _pdfService.PrintOrdersToPdf(stream, orders, _workContext.WorkingLanguage.Id,
- _workContext.CurrentVendor.Id);
+ await _pdfService.PrintOrdersToPdf(stream, orders, _workContextAccessor.WorkContext.WorkingLanguage.Id,
+ _workContextAccessor.WorkContext.CurrentVendor.Id);
bytes = stream.ToArray();
}
diff --git a/src/Web/Grand.Web.Vendor/Controllers/ProductController.cs b/src/Web/Grand.Web.Vendor/Controllers/ProductController.cs
index b01637e4f..94bba619e 100644
--- a/src/Web/Grand.Web.Vendor/Controllers/ProductController.cs
+++ b/src/Web/Grand.Web.Vendor/Controllers/ProductController.cs
@@ -34,7 +34,7 @@ public class ProductController : BaseVendorController
IProductViewModelService productViewModelService,
IProductService productService,
IInventoryManageService inventoryManageService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ILanguageService languageService,
ITranslationService translationService,
IProductReservationService productReservationService,
@@ -46,7 +46,7 @@ public class ProductController : BaseVendorController
_productViewModelService = productViewModelService;
_productService = productService;
_inventoryManageService = inventoryManageService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_languageService = languageService;
_translationService = translationService;
_productReservationService = productReservationService;
@@ -63,7 +63,7 @@ public class ProductController : BaseVendorController
private readonly IProductViewModelService _productViewModelService;
private readonly IProductService _productService;
private readonly IInventoryManageService _inventoryManageService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ILanguageService _languageService;
private readonly ITranslationService _translationService;
private readonly IProductReservationService _productReservationService;
@@ -81,7 +81,7 @@ public class ProductController : BaseVendorController
if (product == null) return Task.FromResult((false, "Product not exists"));
//a vendor should have access only to his products
- return product.VendorId != _workContext.CurrentVendor.Id
+ return product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id
? Task.FromResult((false, "This is not your product"))
: Task.FromResult<(bool allow, string message)>((true, null));
}
@@ -161,7 +161,7 @@ public class ProductController : BaseVendorController
public async Task<IActionResult> Edit(string id)
{
var product = await _productService.GetProductById(id, true);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
//No product found with the specified id
return RedirectToAction("List");
@@ -189,7 +189,7 @@ public class ProductController : BaseVendorController
public async Task<IActionResult> Edit(ProductModel model, bool continueEditing)
{
var product = await _productService.GetProductById(model.Id, true);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
//No product found with the specified id
return RedirectToAction("List");
@@ -226,7 +226,7 @@ public class ProductController : BaseVendorController
public async Task<IActionResult> Delete(string id)
{
var product = await _productService.GetProductById(id, true);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
//No product found with the specified id
return RedirectToAction("List");
@@ -260,7 +260,7 @@ public class ProductController : BaseVendorController
{
var originalProduct = await _productService.GetProductById(copyModel.Id, true);
//a vendor should have access only to his products
- if (originalProduct == null || originalProduct.VendorId != _workContext.CurrentVendor.Id)
+ if (originalProduct == null || originalProduct.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
return RedirectToAction("List");
var newProduct = await copyProductService.CopyProduct(originalProduct,
@@ -321,7 +321,7 @@ public class ProductController : BaseVendorController
var products = await _productService.GetProductsByIds(Enumerable.ToArray(rangeArray), true);
for (var i = 0; i <= products.Count - 1; i++)
{
- if (products[i].VendorId != _workContext.CurrentVendor.Id) continue;
+ if (products[i].VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id) continue;
result += products[i].Name;
if (i != products.Count - 1)
@@ -972,7 +972,7 @@ public class ProductController : BaseVendorController
return ErrorForKendoGridJson(permission.message);
var vendorId = "";
- if (_workContext.CurrentVendor != null) vendorId = _workContext.CurrentVendor.Id;
+ if (_workContextAccessor.WorkContext.CurrentVendor != null) vendorId = _workContextAccessor.WorkContext.CurrentVendor.Id;
var associatedProducts = await _productService.GetAssociatedProducts(productId,
vendorId: vendorId,
@@ -1001,7 +1001,7 @@ public class ProductController : BaseVendorController
if (ModelState.IsValid)
{
var associatedProduct = await _productService.GetProductById(model.Id);
- if (associatedProduct == null || associatedProduct.VendorId != _workContext.CurrentVendor.Id)
+ if (associatedProduct == null || associatedProduct.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No associated product found with the specified id");
associatedProduct.DisplayOrder = model.DisplayOrder;
@@ -1020,7 +1020,7 @@ public class ProductController : BaseVendorController
if (ModelState.IsValid)
{
var product = await _productService.GetProductById(model.Id);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No associated product found with the specified id");
await _productViewModelService.DeleteAssociatedProduct(product);
@@ -1102,7 +1102,7 @@ public class ProductController : BaseVendorController
var product = await _productService.GetProductById(objectId);
//a vendor should have access only to his products
- if (product.VendorId != _workContext.CurrentVendor.Id)
+ if (product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
return Json(new {
success = false,
message = "Access denied - vendor permissions"
@@ -1446,7 +1446,7 @@ public class ProductController : BaseVendorController
}
//a vendor should have access only to his products
- products = products.Where(p => p.VendorId == _workContext.CurrentVendor.Id).ToList();
+ products = products.Where(p => p.VendorId == _workContextAccessor.WorkContext.CurrentVendor.Id).ToList();
var bytes = await exportManager.Export(products);
return File(bytes, "text/xls", "products.xlsx");
@@ -1672,7 +1672,7 @@ public class ProductController : BaseVendorController
return Content("Empty tier price");
//a vendor should have access only to his products
- if (product.VendorId != _workContext.CurrentVendor.Id)
+ if (product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
return Content("This is not your product");
var model = tierPrice.ToModel(_dateTimeService);
@@ -1803,7 +1803,7 @@ public class ProductController : BaseVendorController
throw new ArgumentException("No product attribute mapping found with the specified id");
//a vendor should have access only to his products
- if (product.VendorId != _workContext.CurrentVendor.Id)
+ if (product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
return Content("This is not your product");
await productAttributeService.DeleteProductAttributeMapping(productAttributeMapping, product.Id);
@@ -1909,7 +1909,7 @@ public class ProductController : BaseVendorController
[FromServices] IProductAttributeService productAttributeService)
{
var product = await _productService.GetProductById(productId);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No product found with the specified id");
var productAttributeMapping =
@@ -2036,7 +2036,7 @@ public class ProductController : BaseVendorController
ProductModel.ProductAttributeValueModel model)
{
var product = await _productService.GetProductById(productId);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No product found with the specified id");
var pav = product.ProductAttributeMappings.FirstOrDefault(x => x.Id == model.ProductAttributeMappingId)
@@ -2063,7 +2063,7 @@ public class ProductController : BaseVendorController
[FromServices] IProductAttributeService productAttributeService)
{
var product = await _productService.GetProductById(productId);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No product found with the specified id");
var pav = product.ProductAttributeMappings.FirstOrDefault(x => x.Id == pam)?.ProductAttributeValues
@@ -2106,7 +2106,7 @@ public class ProductController : BaseVendorController
ProductModel.ProductAttributeValueModel.AssociateProductToAttributeValueModel model)
{
var associatedProduct = await _productService.GetProductById(model.AssociatedToProductId);
- if (associatedProduct == null || associatedProduct.VendorId != _workContext.CurrentVendor.Id)
+ if (associatedProduct == null || associatedProduct.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
return Content("Cannot load a product");
return Content("");
@@ -2140,7 +2140,7 @@ public class ProductController : BaseVendorController
[FromServices] IProductAttributeService productAttributeService)
{
var product = await _productService.GetProductById(productId);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No product found with the specified id");
var combination = product.ProductAttributeCombinations.FirstOrDefault(x => x.Id == id);
@@ -2181,7 +2181,7 @@ public class ProductController : BaseVendorController
ProductAttributeCombinationModel model)
{
var product = await _productService.GetProductById(productId);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
//No product found with the specified id
return RedirectToAction("List", "Product");
@@ -2200,7 +2200,7 @@ public class ProductController : BaseVendorController
public async Task<IActionResult> GenerateAllAttributeCombinations(string productId)
{
var product = await _productService.GetProductById(productId);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No product found with the specified id");
await _productViewModelService.GenerateAllAttributeCombinations(product);
@@ -2213,7 +2213,7 @@ public class ProductController : BaseVendorController
public async Task<IActionResult> ClearAllAttributeCombinations(string productId)
{
var product = await _productService.GetProductById(productId);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No product found with the specified id");
if (ModelState.IsValid)
@@ -2304,7 +2304,7 @@ public class ProductController : BaseVendorController
string productAttributeCombinationId, string id)
{
var product = await _productService.GetProductById(productId);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No product found with the specified id");
var combination =
@@ -2363,7 +2363,7 @@ public class ProductController : BaseVendorController
public async Task<IActionResult> GenerateCalendar(ProductModel.GenerateCalendarModel model)
{
var product = await _productService.GetProductById(model.ProductId);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No product found with the specified id");
var reservations =
@@ -2494,7 +2494,7 @@ public class ProductController : BaseVendorController
public async Task<IActionResult> ClearCalendar(string productId)
{
var product = await _productService.GetProductById(productId);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No product found with the specified id");
var toDelete = await _productReservationService.GetProductReservationsByProductId(productId, true, null);
@@ -2507,7 +2507,7 @@ public class ProductController : BaseVendorController
public async Task<IActionResult> ClearOld(string productId)
{
var product = await _productService.GetProductById(productId);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No product found with the specified id");
var toDelete =
@@ -2523,7 +2523,7 @@ public class ProductController : BaseVendorController
public async Task<IActionResult> ProductReservationDelete(ProductModel.ReservationModel model)
{
var product = await _productService.GetProductById(model.ProductId);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No product found with the specified id");
var toDelete = await _productReservationService.GetProductReservation(model.ReservationId);
@@ -2550,7 +2550,7 @@ public class ProductController : BaseVendorController
public async Task<IActionResult> ListBids(DataSourceRequest command, string productId)
{
var product = await _productService.GetProductById(productId);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No product found with the specified id");
var (bidModels, totalCount) =
@@ -2567,7 +2567,7 @@ public class ProductController : BaseVendorController
public async Task<IActionResult> BidDelete(ProductModel.BidModel model)
{
var product = await _productService.GetProductById(model.ProductId);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id)
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentException("No product found with the specified id");
var toDelete = await _auctionService.GetBid(model.BidId);
diff --git a/src/Web/Grand.Web.Vendor/Controllers/ReportsController.cs b/src/Web/Grand.Web.Vendor/Controllers/ReportsController.cs
index a6885da28..1bafab70f 100644
--- a/src/Web/Grand.Web.Vendor/Controllers/ReportsController.cs
+++ b/src/Web/Grand.Web.Vendor/Controllers/ReportsController.cs
@@ -34,12 +34,12 @@ public class ReportsController : BaseVendorController
private readonly IProductsReportService _productsReportService;
private readonly IStockQuantityService _stockQuantityService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IEnumTranslationService _enumTranslationService;
public ReportsController(IOrderReportService orderReportService,
IProductsReportService productsReportService,
ICustomerReportService customerReportService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IPriceFormatter priceFormatter,
IProductService productService,
IProductAttributeFormatter productAttributeFormatter,
@@ -55,7 +55,7 @@ public class ReportsController : BaseVendorController
_orderReportService = orderReportService;
_productsReportService = productsReportService;
_customerReportService = customerReportService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_priceFormatter = priceFormatter;
_productService = productService;
_productAttributeFormatter = productAttributeFormatter;
@@ -74,7 +74,7 @@ public class ReportsController : BaseVendorController
int pageSize, int orderBy)
{
var items = await _orderReportService.BestSellersReport(
- vendorId: _workContext.CurrentVendor.Id,
+ vendorId: _workContextAccessor.WorkContext.CurrentVendor.Id,
orderBy: orderBy,
pageIndex: pageIndex,
pageSize: pageSize,
@@ -156,7 +156,7 @@ public class ReportsController : BaseVendorController
ps: paymentStatus,
billingCountryId: model.BillingCountryId,
orderBy: 2,
- vendorId: _workContext.CurrentVendor.Id,
+ vendorId: _workContextAccessor.WorkContext.CurrentVendor.Id,
pageIndex: command.Page - 1,
pageSize: command.PageSize,
showHidden: true,
@@ -174,9 +174,9 @@ public class ReportsController : BaseVendorController
var product = await _productService.GetProductById(x.ProductId);
if (product != null)
m.ProductName = product.Name;
- if (_workContext.CurrentVendor != null)
+ if (_workContextAccessor.WorkContext.CurrentVendor != null)
{
- if (product?.VendorId == _workContext.CurrentVendor.Id)
+ if (product?.VendorId == _workContextAccessor.WorkContext.CurrentVendor.Id)
result.Add(m);
}
else
@@ -211,7 +211,7 @@ public class ReportsController : BaseVendorController
: _dateTimeService.ConvertToUtcTime(model.EndDate.Value, _dateTimeService.CurrentTimeZone).AddDays(1);
- var items = await _orderReportService.ProductsNeverSold("", _workContext.CurrentVendor.Id,
+ var items = await _orderReportService.ProductsNeverSold("", _workContextAccessor.WorkContext.CurrentVendor.Id,
startDateValue, endDateValue,
command.Page - 1, command.PageSize, true);
var gridModel = new DataSourceResult {
@@ -253,7 +253,7 @@ public class ReportsController : BaseVendorController
var paymentStatus = model.PaymentStatusId > 0 ? (PaymentStatus?)model.PaymentStatusId : null;
var items = await _orderReportService.GetCountryReport(
- vendorId: _workContext.CurrentVendor.Id,
+ vendorId: _workContextAccessor.WorkContext.CurrentVendor.Id,
ps: paymentStatus,
startTimeUtc: startDateValue,
endTimeUtc: endDateValue);
@@ -287,7 +287,7 @@ public class ReportsController : BaseVendorController
[HttpPost]
public async Task<IActionResult> LowStockReportList(DataSourceRequest command)
{
- var lowStockProducts = await _productsReportService.LowStockProducts(_workContext.CurrentVendor.Id);
+ var lowStockProducts = await _productsReportService.LowStockProducts(_workContextAccessor.WorkContext.CurrentVendor.Id);
var models = new List<LowStockProductModel>();
//products
@@ -311,7 +311,7 @@ public class ReportsController : BaseVendorController
Id = product.Id,
Name = product.Name,
Attributes = await _productAttributeFormatter.FormatAttributes(product, combination.Attributes,
- _workContext.CurrentCustomer, "<br />", true, true, true, false),
+ _workContextAccessor.WorkContext.CurrentCustomer, "<br />", true, true, true, false),
ManageInventoryMethod = _enumTranslationService.GetTranslationEnum(product.ManageInventoryMethodId),
StockQuantity = combination.StockQuantity,
Published = product.Published
@@ -357,7 +357,7 @@ public class ReportsController : BaseVendorController
var paymentStatus = model.PaymentStatusId > 0 ? (PaymentStatus?)model.PaymentStatusId : null;
- var items = _customerReportService.GetBestCustomersReport("", _workContext.CurrentVendor.Id, startDateValue,
+ var items = _customerReportService.GetBestCustomersReport("", _workContextAccessor.WorkContext.CurrentVendor.Id, startDateValue,
endDateValue,
null, paymentStatus, null, 2, command.Page - 1, command.PageSize);
diff --git a/src/Web/Grand.Web.Vendor/Controllers/ShipmentController.cs b/src/Web/Grand.Web.Vendor/Controllers/ShipmentController.cs
index dfb59ade9..00d026bd9 100644
--- a/src/Web/Grand.Web.Vendor/Controllers/ShipmentController.cs
+++ b/src/Web/Grand.Web.Vendor/Controllers/ShipmentController.cs
@@ -27,7 +27,7 @@ public class ShipmentController : BaseVendorController
IShipmentViewModelService shipmentViewModelService,
IOrderService orderService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IPdfService pdfService,
IShipmentService shipmentService,
IDateTimeService dateTimeService,
@@ -36,7 +36,7 @@ public class ShipmentController : BaseVendorController
_shipmentViewModelService = shipmentViewModelService;
_orderService = orderService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_pdfService = pdfService;
_shipmentService = shipmentService;
_dateTimeService = dateTimeService;
@@ -48,7 +48,7 @@ public class ShipmentController : BaseVendorController
private readonly IShipmentViewModelService _shipmentViewModelService;
private readonly IOrderService _orderService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IPdfService _pdfService;
private readonly IShipmentService _shipmentService;
private readonly IDateTimeService _dateTimeService;
@@ -85,14 +85,14 @@ public class ShipmentController : BaseVendorController
public async Task<IActionResult> ShipmentsByOrder(string orderId)
{
var order = await _orderService.GetOrderById(orderId);
- if (order == null || order.Deleted || !_workContext.HasAccessToOrder(order))
+ if (order == null || order.Deleted || !_workContextAccessor.WorkContext.HasAccessToOrder(order))
throw new ArgumentException("No order found with the specified id");
//shipments
var shipmentModels = new List<ShipmentModel>();
var shipments = (await _shipmentService.GetShipmentsByOrder(orderId))
//a vendor should have access only to his products
- .Where(s => _workContext.HasAccessToShipment(s))
+ .Where(s => _workContextAccessor.WorkContext.HasAccessToShipment(s))
.OrderBy(s => s.CreatedOnUtc)
.ToList();
@@ -111,7 +111,7 @@ public class ShipmentController : BaseVendorController
public async Task<IActionResult> ShipmentsItemsByShipmentId(string shipmentId)
{
var shipment = await _shipmentService.GetShipmentById(shipmentId);
- if (shipment == null || !_workContext.HasAccessToShipment(shipment))
+ if (shipment == null || !_workContextAccessor.WorkContext.HasAccessToShipment(shipment))
throw new ArgumentException("No shipment found with the specified id");
//shipments
@@ -128,7 +128,7 @@ public class ShipmentController : BaseVendorController
public async Task<IActionResult> AddShipment(string orderId)
{
var order = await _orderService.GetOrderById(orderId);
- if (order == null || order.Deleted || !_workContext.HasAccessToOrder(order))
+ if (order == null || order.Deleted || !_workContextAccessor.WorkContext.HasAccessToOrder(order))
//No order found with the specified id
return RedirectToAction("List");
@@ -145,12 +145,12 @@ public class ShipmentController : BaseVendorController
return RedirectToAction("AddShipment", new { orderId = model.OrderId });
var order = await _orderService.GetOrderById(model.OrderId);
- if (order == null || order.Deleted || !_workContext.HasAccessToOrder(order))
+ if (order == null || order.Deleted || !_workContextAccessor.WorkContext.HasAccessToOrder(order))
//No order found with the specified id
return RedirectToAction("List");
//a vendor should have access only to his products
- var orderItems = order.OrderItems.Where(_workContext.HasAccessToOrderItem).ToList();
+ var orderItems = order.OrderItems.Where(_workContextAccessor.WorkContext.HasAccessToOrderItem).ToList();
var (shipment, totalWeight) =
await _shipmentViewModelService.PrepareShipment(order, orderItems.ToList(), model);
@@ -187,7 +187,7 @@ public class ShipmentController : BaseVendorController
public async Task<IActionResult> ShipmentDetails(string id)
{
var shipment = await _shipmentService.GetShipmentById(id);
- if (shipment == null || !_workContext.HasAccessToShipment(shipment))
+ if (shipment == null || !_workContextAccessor.WorkContext.HasAccessToShipment(shipment))
//No shipment found with the specified id
return RedirectToAction("List");
@@ -200,7 +200,7 @@ public class ShipmentController : BaseVendorController
public async Task<IActionResult> DeleteShipment(string id)
{
var shipment = await _shipmentService.GetShipmentById(id);
- if (shipment == null || !_workContext.HasAccessToShipment(shipment))
+ if (shipment == null || !_workContextAccessor.WorkContext.HasAccessToShipment(shipment))
//No shipment found with the specified id
return RedirectToAction("List");
@@ -225,7 +225,7 @@ public class ShipmentController : BaseVendorController
return RedirectToAction("ShipmentDetails", new { id = model.Id });
var shipment = await _shipmentService.GetShipmentById(model.Id);
- if (shipment == null || !_workContext.HasAccessToShipment(shipment))
+ if (shipment == null || !_workContextAccessor.WorkContext.HasAccessToShipment(shipment))
//No shipment found with the specified id
return RedirectToAction("List");
@@ -243,7 +243,7 @@ public class ShipmentController : BaseVendorController
return RedirectToAction("ShipmentDetails", new { id = model.Id });
var shipment = await _shipmentService.GetShipmentById(model.Id);
- if (shipment == null || !_workContext.HasAccessToShipment(shipment))
+ if (shipment == null || !_workContextAccessor.WorkContext.HasAccessToShipment(shipment))
//No shipment found with the specified id
return RedirectToAction("List");
@@ -258,7 +258,7 @@ public class ShipmentController : BaseVendorController
public async Task<IActionResult> SetAsShipped(string id)
{
var shipment = await _shipmentService.GetShipmentById(id);
- if (shipment == null || !_workContext.HasAccessToShipment(shipment))
+ if (shipment == null || !_workContextAccessor.WorkContext.HasAccessToShipment(shipment))
//No shipment found with the specified id
return RedirectToAction("List");
@@ -283,7 +283,7 @@ public class ShipmentController : BaseVendorController
return RedirectToAction("ShipmentDetails", new { id = model.Id });
var shipment = await _shipmentService.GetShipmentById(model.Id);
- if (shipment == null || !_workContext.HasAccessToShipment(shipment))
+ if (shipment == null || !_workContextAccessor.WorkContext.HasAccessToShipment(shipment))
//No shipment found with the specified id
return RedirectToAction("List");
@@ -308,7 +308,7 @@ public class ShipmentController : BaseVendorController
public async Task<IActionResult> SetAsDelivered(string id)
{
var shipment = await _shipmentService.GetShipmentById(id);
- if (shipment == null || !_workContext.HasAccessToShipment(shipment))
+ if (shipment == null || !_workContextAccessor.WorkContext.HasAccessToShipment(shipment))
//No shipment found with the specified id
return RedirectToAction("List");
@@ -334,7 +334,7 @@ public class ShipmentController : BaseVendorController
return RedirectToAction("ShipmentDetails", new { id = model.Id });
var shipment = await _shipmentService.GetShipmentById(model.Id);
- if (shipment == null || !_workContext.HasAccessToShipment(shipment))
+ if (shipment == null || !_workContextAccessor.WorkContext.HasAccessToShipment(shipment))
//No shipment found with the specified id
return RedirectToAction("List");
@@ -358,7 +358,7 @@ public class ShipmentController : BaseVendorController
public async Task<IActionResult> PdfPackagingSlip(string shipmentId)
{
var shipment = await _shipmentService.GetShipmentById(shipmentId);
- if (shipment == null || !_workContext.HasAccessToShipment(shipment))
+ if (shipment == null || !_workContextAccessor.WorkContext.HasAccessToShipment(shipment))
//no shipment found with the specified id
return RedirectToAction("List");
@@ -369,7 +369,7 @@ public class ShipmentController : BaseVendorController
byte[] bytes;
using (var stream = new MemoryStream())
{
- await _pdfService.PrintPackagingSlipsToPdf(stream, shipments, _workContext.WorkingLanguage.Id);
+ await _pdfService.PrintPackagingSlipsToPdf(stream, shipments, _workContextAccessor.WorkContext.WorkingLanguage.Id);
bytes = stream.ToArray();
}
@@ -394,7 +394,7 @@ public class ShipmentController : BaseVendorController
using (var stream = new MemoryStream())
{
await _pdfService.PrintPackagingSlipsToPdf(stream, shipments.shipments.ToList(),
- _workContext.WorkingLanguage.Id);
+ _workContextAccessor.WorkContext.WorkingLanguage.Id);
bytes = stream.ToArray();
}
@@ -418,7 +418,7 @@ public class ShipmentController : BaseVendorController
//a vendor should have access only to his shipments
var shipmentsAccess =
(from item in shipments
- where _workContext.HasAccessToShipment(item)
+ where _workContextAccessor.WorkContext.HasAccessToShipment(item)
select item).ToList();
//ensure that we at least one shipment selected
@@ -431,7 +431,7 @@ public class ShipmentController : BaseVendorController
byte[] bytes;
using (var stream = new MemoryStream())
{
- await _pdfService.PrintPackagingSlipsToPdf(stream, shipmentsAccess, _workContext.WorkingLanguage.Id);
+ await _pdfService.PrintPackagingSlipsToPdf(stream, shipmentsAccess, _workContextAccessor.WorkContext.WorkingLanguage.Id);
bytes = stream.ToArray();
}
@@ -448,7 +448,7 @@ public class ShipmentController : BaseVendorController
//a vendor should have access only to his shipments
shipmentsAccess.AddRange(from item in shipments
- where _workContext.HasAccessToShipment(item)
+ where _workContextAccessor.WorkContext.HasAccessToShipment(item)
select item);
foreach (var shipment in shipmentsAccess)
@@ -475,7 +475,7 @@ public class ShipmentController : BaseVendorController
//a vendor should have access only to his shipments
shipmentsAccess.AddRange(
from item in shipments
- where _workContext.HasAccessToShipment(item)
+ where _workContextAccessor.WorkContext.HasAccessToShipment(item)
select item);
foreach (var shipment in shipmentsAccess)
@@ -498,7 +498,7 @@ public class ShipmentController : BaseVendorController
public async Task<IActionResult> ShipmentNotesSelect(string shipmentId)
{
var shipment = await _shipmentService.GetShipmentById(shipmentId);
- if (shipment == null || !_workContext.HasAccessToShipment(shipment))
+ if (shipment == null || !_workContextAccessor.WorkContext.HasAccessToShipment(shipment))
throw new ArgumentException("No shipment found with the specified id");
//shipment notes
@@ -515,7 +515,7 @@ public class ShipmentController : BaseVendorController
string message)
{
var shipment = await _shipmentService.GetShipmentById(shipmentId);
- if (shipment == null || !_workContext.HasAccessToShipment(shipment))
+ if (shipment == null || !_workContextAccessor.WorkContext.HasAccessToShipment(shipment))
return Json(new { Result = false });
await _shipmentViewModelService.InsertShipmentNote(shipment, displayToCustomer, message);
@@ -528,7 +528,7 @@ public class ShipmentController : BaseVendorController
public async Task<IActionResult> ShipmentNoteDelete(string id, string shipmentId)
{
var shipment = await _shipmentService.GetShipmentById(shipmentId);
- if (shipment == null || !_workContext.HasAccessToShipment(shipment))
+ if (shipment == null || !_workContextAccessor.WorkContext.HasAccessToShipment(shipment))
throw new ArgumentException("No shipment found with the specified id");
await _shipmentViewModelService.DeleteShipmentNote(shipment, id);
diff --git a/src/Web/Grand.Web.Vendor/Controllers/VendorInfoController.cs b/src/Web/Grand.Web.Vendor/Controllers/VendorInfoController.cs
index bb01fa187..185286b7d 100644
--- a/src/Web/Grand.Web.Vendor/Controllers/VendorInfoController.cs
+++ b/src/Web/Grand.Web.Vendor/Controllers/VendorInfoController.cs
@@ -22,7 +22,7 @@ public class VendorInfoController : BaseVendorController
ITranslationService translationService,
IVendorService vendorService,
ILanguageService languageService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ICountryService countryService,
VendorSettings vendorSettings,
ISeNameService seNameService)
@@ -30,7 +30,7 @@ public class VendorInfoController : BaseVendorController
_translationService = translationService;
_vendorService = vendorService;
_languageService = languageService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_countryService = countryService;
_vendorSettings = vendorSettings;
_seNameService = seNameService;
@@ -40,7 +40,7 @@ public class VendorInfoController : BaseVendorController
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ITranslationService _translationService;
private readonly IVendorService _vendorService;
private readonly ILanguageService _languageService;
@@ -121,7 +121,7 @@ public class VendorInfoController : BaseVendorController
if (!_vendorSettings.AllowVendorsToEditInfo)
throw new Exception("Vendor can't edit info");
- var vendor = await _vendorService.GetVendorById(_workContext.CurrentVendor.Id);
+ var vendor = await _vendorService.GetVendorById(_workContextAccessor.WorkContext.CurrentVendor.Id);
if (vendor == null || vendor.Deleted)
throw new ArgumentNullException(nameof(vendor));
@@ -151,7 +151,7 @@ public class VendorInfoController : BaseVendorController
throw new Exception("Vendor can't edit info");
var vendor = await _vendorService.GetVendorById(model.Id);
- if (vendor == null || vendor.Deleted || vendor.Id != _workContext.CurrentVendor.Id)
+ if (vendor == null || vendor.Deleted || vendor.Id != _workContextAccessor.WorkContext.CurrentVendor.Id)
throw new ArgumentNullException(nameof(vendor));
if (ModelState.IsValid)
diff --git a/src/Web/Grand.Web.Vendor/Controllers/VendorReviewController.cs b/src/Web/Grand.Web.Vendor/Controllers/VendorReviewController.cs
index 32e51919d..ac3b603a7 100644
--- a/src/Web/Grand.Web.Vendor/Controllers/VendorReviewController.cs
+++ b/src/Web/Grand.Web.Vendor/Controllers/VendorReviewController.cs
@@ -20,12 +20,12 @@ public class VendorReviewController : BaseVendorController
IVendorReviewViewModelService vendorReviewViewModelService,
IVendorService vendorService,
ITranslationService translationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_vendorReviewViewModelService = vendorReviewViewModelService;
_vendorService = vendorService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
#endregion
@@ -35,7 +35,7 @@ public class VendorReviewController : BaseVendorController
private readonly IVendorReviewViewModelService _vendorReviewViewModelService;
private readonly IVendorService _vendorService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
#endregion Fields
@@ -73,7 +73,7 @@ public class VendorReviewController : BaseVendorController
{
var vendorReview = await _vendorService.GetVendorReviewById(id);
- if (vendorReview == null || vendorReview.VendorId != _workContext.CurrentVendor.Id)
+ if (vendorReview == null || vendorReview.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
//No vendor review found with the specified id
return RedirectToAction("List");
@@ -88,7 +88,7 @@ public class VendorReviewController : BaseVendorController
public async Task<IActionResult> Edit(VendorReviewModel model, bool continueEditing)
{
var vendorReview = await _vendorService.GetVendorReviewById(model.Id);
- if (vendorReview == null || vendorReview.VendorId != _workContext.CurrentVendor.Id)
+ if (vendorReview == null || vendorReview.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
//No vendor review found with the specified id
return RedirectToAction("List");
@@ -112,7 +112,7 @@ public class VendorReviewController : BaseVendorController
public async Task<IActionResult> Delete(string id)
{
var vendorReview = await _vendorService.GetVendorReviewById(id);
- if (vendorReview == null || vendorReview.VendorId != _workContext.CurrentVendor.Id)
+ if (vendorReview == null || vendorReview.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
//No vendor review found with the specified id
return RedirectToAction("List");
diff --git a/src/Web/Grand.Web.Vendor/Services/MerchandiseReturnViewModelService.cs b/src/Web/Grand.Web.Vendor/Services/MerchandiseReturnViewModelService.cs
index 4e3cf49ce..391acd1a2 100644
--- a/src/Web/Grand.Web.Vendor/Services/MerchandiseReturnViewModelService.cs
+++ b/src/Web/Grand.Web.Vendor/Services/MerchandiseReturnViewModelService.cs
@@ -27,7 +27,7 @@ public class MerchandiseReturnViewModelService : IMerchandiseReturnViewModelServ
#region Fields
private readonly IOrderService _orderService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IProductService _productService;
private readonly IDateTimeService _dateTimeService;
private readonly ICustomerService _customerService;
@@ -49,7 +49,7 @@ public class MerchandiseReturnViewModelService : IMerchandiseReturnViewModelServ
public MerchandiseReturnViewModelService(
IOrderService orderService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IProductService productService,
ICustomerService customerService,
IDateTimeService dateTimeService,
@@ -66,7 +66,7 @@ public class MerchandiseReturnViewModelService : IMerchandiseReturnViewModelServ
IEnumTranslationService enumTranslationService)
{
_orderService = orderService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_productService = productService;
_customerService = customerService;
_dateTimeService = dateTimeService;
@@ -154,7 +154,7 @@ public class MerchandiseReturnViewModelService : IMerchandiseReturnViewModelServ
var merchandiseReturns = await _merchandiseReturnService.SearchMerchandiseReturns(
customerId: customerId,
- vendorId: _workContext.CurrentVendor.Id,
+ vendorId: _workContextAccessor.WorkContext.CurrentVendor.Id,
rs: model.SearchMerchandiseReturnStatusId >= 0
? (MerchandiseReturnStatus?)model.SearchMerchandiseReturnStatusId
: null,
diff --git a/src/Web/Grand.Web.Vendor/Services/OrderViewModelService.cs b/src/Web/Grand.Web.Vendor/Services/OrderViewModelService.cs
index f7068db54..beeb3e32d 100644
--- a/src/Web/Grand.Web.Vendor/Services/OrderViewModelService.cs
+++ b/src/Web/Grand.Web.Vendor/Services/OrderViewModelService.cs
@@ -38,7 +38,7 @@ public class OrderViewModelService : IOrderViewModelService
private readonly IDateTimeService _dateTimeService;
private readonly IPriceFormatter _priceFormatter;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ICurrencyService _currencyService;
private readonly IPaymentService _paymentService;
private readonly ICountryService _countryService;
@@ -67,7 +67,7 @@ public class OrderViewModelService : IOrderViewModelService
IDateTimeService dateTimeService,
IPriceFormatter priceFormatter,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ICurrencyService currencyService,
IPaymentService paymentService,
ICountryService countryService,
@@ -91,7 +91,7 @@ public class OrderViewModelService : IOrderViewModelService
_dateTimeService = dateTimeService;
_priceFormatter = priceFormatter;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_currencyService = currencyService;
_paymentService = paymentService;
_countryService = countryService;
@@ -216,7 +216,7 @@ public class OrderViewModelService : IOrderViewModelService
//load orders
var orders = await _orderService.SearchOrders(
- vendorId: _workContext.CurrentVendor.Id,
+ vendorId: _workContextAccessor.WorkContext.CurrentVendor.Id,
customerId: model.CustomerId,
productId: model.ProductId,
warehouseId: model.WarehouseId,
@@ -321,7 +321,7 @@ public class OrderViewModelService : IOrderViewModelService
model.BillingAddress = await order.BillingAddress.ToModel(_countryService);
model.BillingAddress.FormattedCustomAddressAttributes =
- await _addressAttributeParser.FormatAttributes(_workContext.WorkingLanguage,
+ await _addressAttributeParser.FormatAttributes(_workContextAccessor.WorkContext.WorkingLanguage,
order.BillingAddress.Attributes);
model.BillingAddress.NameEnabled = _addressSettings.NameEnabled;
model.BillingAddress.FirstNameEnabled = true;
@@ -361,7 +361,7 @@ public class OrderViewModelService : IOrderViewModelService
{
model.ShippingAddress = await order.ShippingAddress.ToModel(_countryService);
model.ShippingAddress.FormattedCustomAddressAttributes =
- await _addressAttributeParser.FormatAttributes(_workContext.WorkingLanguage,
+ await _addressAttributeParser.FormatAttributes(_workContextAccessor.WorkContext.WorkingLanguage,
order.ShippingAddress.Attributes);
model.ShippingAddress.NameEnabled = _addressSettings.NameEnabled;
model.ShippingAddress.FirstNameEnabled = true;
@@ -429,7 +429,7 @@ public class OrderViewModelService : IOrderViewModelService
model.CheckoutAttributeInfo = order.CheckoutAttributeDescription;
var hasDownloadableItems = false;
var products = order.OrderItems
- .Where(orderItem => orderItem.VendorId == _workContext.CurrentVendor.Id)
+ .Where(orderItem => orderItem.VendorId == _workContextAccessor.WorkContext.CurrentVendor.Id)
.ToList();
foreach (var orderItem in products)
@@ -553,7 +553,7 @@ public class OrderViewModelService : IOrderViewModelService
//load orders
var orders = await _orderService.SearchOrders(
- vendorId: _workContext.CurrentVendor.Id,
+ vendorId: _workContextAccessor.WorkContext.CurrentVendor.Id,
productId: model.ProductId,
warehouseId: model.WarehouseId,
paymentMethodSystemName: model.PaymentMethodSystemName,
diff --git a/src/Web/Grand.Web.Vendor/Services/ProductViewModelService.cs b/src/Web/Grand.Web.Vendor/Services/ProductViewModelService.cs
index de51077c7..239c1b63a 100644
--- a/src/Web/Grand.Web.Vendor/Services/ProductViewModelService.cs
+++ b/src/Web/Grand.Web.Vendor/Services/ProductViewModelService.cs
@@ -61,7 +61,7 @@ public class ProductViewModelService : IProductViewModelService
private readonly TaxSettings _taxSettings;
private readonly ITranslationService _translationService;
private readonly IWarehouseService _warehouseService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ISeNameService _seNameService;
private readonly IEnumTranslationService _enumTranslationService;
@@ -80,7 +80,7 @@ public class ProductViewModelService : IProductViewModelService
ITranslationService translationService,
IProductLayoutService productLayoutService,
ISpecificationAttributeService specificationAttributeService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IWarehouseService warehouseService,
IDeliveryDateService deliveryDateService,
ITaxCategoryService taxCategoryService,
@@ -112,7 +112,7 @@ public class ProductViewModelService : IProductViewModelService
_translationService = translationService;
_productLayoutService = productLayoutService;
_specificationAttributeService = specificationAttributeService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_warehouseService = warehouseService;
_deliveryDateService = deliveryDateService;
_taxCategoryService = taxCategoryService;
@@ -613,7 +613,7 @@ public class ProductViewModelService : IProductViewModelService
categoryIds: categoryIds,
brandId: model.SearchBrandId,
collectionId: model.SearchCollectionId,
- vendorId: _workContext.CurrentVendor.Id,
+ vendorId: _workContextAccessor.WorkContext.CurrentVendor.Id,
warehouseId: model.SearchWarehouseId,
productType: model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null,
keywords: model.SearchProductName,
@@ -674,7 +674,7 @@ public class ProductViewModelService : IProductViewModelService
categoryIds: categoryIds,
brandId: model.SearchBrandId,
collectionId: model.SearchCollectionId,
- vendorId: _workContext.CurrentVendor.Id,
+ vendorId: _workContextAccessor.WorkContext.CurrentVendor.Id,
warehouseId: model.SearchWarehouseId,
productType: model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null,
keywords: model.SearchProductName,
@@ -689,7 +689,7 @@ public class ProductViewModelService : IProductViewModelService
{
//product
var product = model.ToEntity(_dateTimeService);
- product.VendorId = _workContext.CurrentVendor?.Id;
+ product.VendorId = _workContextAccessor.WorkContext.CurrentVendor?.Id;
product.Locales = await _seNameService.TranslationSeNameProperties(model.Locales, product, x => x.Name);
product.SeName = await _seNameService.ValidateSeName(product, model.SeName, product.Name, true);
@@ -750,7 +750,7 @@ public class ProductViewModelService : IProductViewModelService
{
var product = products[i];
//a vendor should have access only to his products
- if (product.VendorId != _workContext.CurrentVendor.Id)
+ if (product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
continue;
await DeleteProduct(product);
@@ -767,7 +767,7 @@ public class ProductViewModelService : IProductViewModelService
ProductModel.AddProductModel model, int pageIndex, int pageSize)
{
var products = await _productService.PrepareProductList(model.SearchCategoryId, model.SearchBrandId,
- model.SearchCollectionId, string.Empty, _workContext.CurrentVendor.Id, model.SearchProductTypeId,
+ model.SearchCollectionId, string.Empty, _workContextAccessor.WorkContext.CurrentVendor.Id, model.SearchProductTypeId,
model.SearchProductName, pageIndex, pageSize);
return (products.Select(x => x.ToModel(_dateTimeService)).ToList(), products.TotalCount);
}
@@ -898,7 +898,7 @@ public class ProductViewModelService : IProductViewModelService
foreach (var id in model.SelectedProductIds)
{
var product = await _productService.GetProductById(id);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id) continue;
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id) continue;
var existingRelatedProducts = productId1.RelatedProducts;
if (model.ProductId == id) continue;
@@ -943,7 +943,7 @@ public class ProductViewModelService : IProductViewModelService
foreach (var id in model.SelectedProductIds)
{
var product = await _productService.GetProductById(id);
- if (product != null && productId1.VendorId == _workContext.CurrentVendor.Id)
+ if (product != null && productId1.VendorId == _workContextAccessor.WorkContext.CurrentVendor.Id)
{
var existingSimilarProducts = productId1.SimilarProducts;
if (model.ProductId != id)
@@ -991,7 +991,7 @@ public class ProductViewModelService : IProductViewModelService
foreach (var id in model.SelectedProductIds)
{
var product = await _productService.GetProductById(id);
- if (product != null && productId1.VendorId == _workContext.CurrentVendor.Id)
+ if (product != null && productId1.VendorId == _workContextAccessor.WorkContext.CurrentVendor.Id)
{
var existingBundleProducts = productId1.BundleProducts;
if (model.ProductId != id)
@@ -1038,7 +1038,7 @@ public class ProductViewModelService : IProductViewModelService
foreach (var id in model.SelectedProductIds)
{
var product = await _productService.GetProductById(id);
- if (product != null && product.VendorId == _workContext.CurrentVendor.Id &&
+ if (product != null && product.VendorId == _workContextAccessor.WorkContext.CurrentVendor.Id &&
crossSellProduct.CrossSellProduct.All(x => x != id))
if (model.ProductId != id)
await _productService.InsertCrossSellProduct(
@@ -1064,7 +1064,7 @@ public class ProductViewModelService : IProductViewModelService
foreach (var id in model.SelectedProductIds)
{
var product = await _productService.GetProductById(id);
- if (product != null && product.VendorId == _workContext.CurrentVendor.Id)
+ if (product != null && product.VendorId == _workContextAccessor.WorkContext.CurrentVendor.Id)
if (mainproduct.RecommendedProduct.All(x => x != id))
if (model.ProductId != id)
await _productService.InsertRecommendedProduct(model.ProductId, id);
@@ -1081,7 +1081,7 @@ public class ProductViewModelService : IProductViewModelService
foreach (var id in model.SelectedProductIds)
{
var product = await _productService.GetProductById(id);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id) continue;
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id) continue;
product.ParentGroupedProductId = model.ProductId;
await _productService.UpdateAssociatedProduct(product);
}
@@ -1152,7 +1152,7 @@ public class ProductViewModelService : IProductViewModelService
var products = (await _productService.SearchProducts(categoryIds: searchCategoryIds,
brandId: model.SearchBrandId,
collectionId: model.SearchCollectionId,
- vendorId: _workContext.CurrentVendor.Id,
+ vendorId: _workContextAccessor.WorkContext.CurrentVendor.Id,
productType: model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null,
keywords: model.SearchProductName,
pageIndex: pageIndex - 1,
@@ -1182,7 +1182,7 @@ public class ProductViewModelService : IProductViewModelService
{
//update
var product = await _productService.GetProductById(pModel.Id, true);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id) continue;
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id) continue;
var prevStockQuantity = _stockQuantityService.GetTotalStockQuantity(product, total: true);
@@ -1212,7 +1212,7 @@ public class ProductViewModelService : IProductViewModelService
{
//delete
var product = await _productService.GetProductById(pModel.Id, true);
- if (product == null || product.VendorId != _workContext.CurrentVendor.Id) continue;
+ if (product == null || product.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id) continue;
await _productService.DeleteProduct(product);
}
@@ -1780,7 +1780,7 @@ public class ProductViewModelService : IProductViewModelService
foreach (var x in product.ProductAttributeCombinations)
{
var attributes = await _productAttributeFormatter.FormatAttributes(product, x.Attributes,
- _workContext.CurrentCustomer, "<br />", true, true, true, false, true, true);
+ _workContextAccessor.WorkContext.CurrentCustomer, "<br />", true, true, true, false, true, true);
var pacModel = new ProductModel.ProductAttributeCombinationModel {
Id = x.Id,
ProductId = product.Id,
@@ -1831,7 +1831,7 @@ public class ProductViewModelService : IProductViewModelService
model.WarehouseInventoryModels = wim;
model.ProductId = product.Id;
model.Attributes = await _productAttributeFormatter.FormatAttributes(product,
- combination.Attributes, _workContext.CurrentCustomer, "<br />", true, true, true, false);
+ combination.Attributes, _workContextAccessor.WorkContext.CurrentCustomer, "<br />", true, true, true, false);
if (model.UseMultipleWarehouses)
foreach (var winv in combination.WarehouseInventory)
{
diff --git a/src/Web/Grand.Web.Vendor/Services/ShipmentViewModelService.cs b/src/Web/Grand.Web.Vendor/Services/ShipmentViewModelService.cs
index 1b55bf2c3..927204c83 100644
--- a/src/Web/Grand.Web.Vendor/Services/ShipmentViewModelService.cs
+++ b/src/Web/Grand.Web.Vendor/Services/ShipmentViewModelService.cs
@@ -32,11 +32,11 @@ public class ShipmentViewModelService : IShipmentViewModelService
private readonly IStockQuantityService _stockQuantityService;
private readonly ITranslationService _translationService;
private readonly IWarehouseService _warehouseService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public ShipmentViewModelService(
IOrderService orderService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
IProductService productService,
IShipmentService shipmentService,
@@ -51,7 +51,7 @@ public class ShipmentViewModelService : IShipmentViewModelService
ShippingProviderSettings shippingProviderSettings)
{
_orderService = orderService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_productService = productService;
_shipmentService = shipmentService;
@@ -104,7 +104,7 @@ public class ShipmentViewModelService : IShipmentViewModelService
if (orderItem == null)
continue;
- if (orderItem.VendorId != _workContext.CurrentVendor.Id)
+ if (orderItem.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id)
continue;
//quantities
@@ -261,7 +261,7 @@ public class ShipmentViewModelService : IShipmentViewModelService
//load shipments
var shipments = await _shipmentService.GetAllShipments(
- vendorId: _workContext.CurrentVendor.Id,
+ vendorId: _workContextAccessor.WorkContext.CurrentVendor.Id,
warehouseId: model.WarehouseId,
shippingCity: model.City,
trackingNumber: model.TrackingNumber,
@@ -301,8 +301,8 @@ public class ShipmentViewModelService : IShipmentViewModelService
var orderItems = order.OrderItems;
//a vendor should have access only to his products
- if (_workContext.CurrentVendor != null && !await _groupService.IsStaff(_workContext.CurrentCustomer))
- orderItems = orderItems.Where(_workContext.HasAccessToOrderItem).ToList();
+ if (_workContextAccessor.WorkContext.CurrentVendor != null && !await _groupService.IsStaff(_workContextAccessor.WorkContext.CurrentCustomer))
+ orderItems = orderItems.Where(_workContextAccessor.WorkContext.HasAccessToOrderItem).ToList();
foreach (var orderItem in orderItems)
{
@@ -498,7 +498,7 @@ public class ShipmentViewModelService : IShipmentViewModelService
DeliveryDateUtc = null,
AdminComment = model.AdminComment,
StoreId = order.StoreId,
- VendorId = _workContext.CurrentVendor.Id
+ VendorId = _workContextAccessor.WorkContext.CurrentVendor.Id
};
double? totalWeight = null;
foreach (var orderItem in orderItems)
diff --git a/src/Web/Grand.Web.Vendor/Services/VendorReviewViewModelService.cs b/src/Web/Grand.Web.Vendor/Services/VendorReviewViewModelService.cs
index 158ef3eb5..003f560ea 100644
--- a/src/Web/Grand.Web.Vendor/Services/VendorReviewViewModelService.cs
+++ b/src/Web/Grand.Web.Vendor/Services/VendorReviewViewModelService.cs
@@ -18,10 +18,10 @@ public class VendorReviewViewModelService : IVendorReviewViewModelService
private readonly IMediator _mediator;
private readonly ITranslationService _translationService;
private readonly IVendorService _vendorService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public VendorReviewViewModelService(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IVendorService vendorService,
ICustomerService customerService,
ITranslationService translationService,
@@ -33,7 +33,7 @@ public class VendorReviewViewModelService : IVendorReviewViewModelService
_translationService = translationService;
_dateTimeService = dateTimeService;
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public virtual async Task PrepareVendorReviewModel(VendorReviewModel model,
@@ -75,7 +75,7 @@ public class VendorReviewViewModelService : IVendorReviewViewModelService
: _dateTimeService.ConvertToUtcTime(model.CreatedOnTo.Value, _dateTimeService.CurrentTimeZone).AddDays(1);
var vendorReviews = await _vendorService.GetAllVendorReviews("", null,
- createdOnFromValue, createdToFromValue, model.SearchText, _workContext.CurrentVendor.Id, pageIndex - 1,
+ createdOnFromValue, createdToFromValue, model.SearchText, _workContextAccessor.WorkContext.CurrentVendor.Id, pageIndex - 1,
pageSize);
var items = new List<VendorReviewModel>();
foreach (var x in vendorReviews)
@@ -115,12 +115,12 @@ public class VendorReviewViewModelService : IVendorReviewViewModelService
foreach (var id in selectedIds)
{
var vendorReview = await _vendorService.GetVendorReviewById(id);
- if (vendorReview == null || vendorReview.VendorId != _workContext.CurrentVendor.Id) continue;
+ if (vendorReview == null || vendorReview.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id) continue;
var previousIsApproved = vendorReview.IsApproved;
vendorReview.IsApproved = true;
await _vendorService.UpdateVendorReview(vendorReview);
- await _vendorService.UpdateVendorReviewTotals(_workContext.CurrentVendor);
+ await _vendorService.UpdateVendorReviewTotals(_workContextAccessor.WorkContext.CurrentVendor);
//raise event (only if it wasn't approved before)
if (!previousIsApproved)
@@ -133,11 +133,11 @@ public class VendorReviewViewModelService : IVendorReviewViewModelService
foreach (var id in selectedIds)
{
var vendorReview = await _vendorService.GetVendorReviewById(id);
- if (vendorReview == null || vendorReview.VendorId != _workContext.CurrentVendor.Id) continue;
+ if (vendorReview == null || vendorReview.VendorId != _workContextAccessor.WorkContext.CurrentVendor.Id) continue;
vendorReview.IsApproved = false;
await _vendorService.UpdateVendorReview(vendorReview);
- await _vendorService.UpdateVendorReviewTotals(_workContext.CurrentVendor);
+ await _vendorService.UpdateVendorReviewTotals(_workContextAccessor.WorkContext.CurrentVendor);
}
}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Vendor/Validators/Catalog/BundleProductModelValidator.cs b/src/Web/Grand.Web.Vendor/Validators/Catalog/BundleProductModelValidator.cs
index 6811df6aa..e2eebd5d1 100644
--- a/src/Web/Grand.Web.Vendor/Validators/Catalog/BundleProductModelValidator.cs
+++ b/src/Web/Grand.Web.Vendor/Validators/Catalog/BundleProductModelValidator.cs
@@ -11,14 +11,14 @@ public class BundleProductModelValidator : BaseGrandValidator<ProductModel.Bundl
{
public BundleProductModelValidator(
IEnumerable<IValidatorConsumer<ProductModel.BundleProductModel>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductBundleId);
if (product == null) return true;
- return product.VendorId == workContext.CurrentVendor.Id;
+ return product.VendorId == workContextAccessor.WorkContext.CurrentVendor.Id;
}).WithMessage(translationService.GetResource("Vendor.Catalog.Products.Permissions"));
}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Vendor/Validators/Catalog/ProductValidVendor.cs b/src/Web/Grand.Web.Vendor/Validators/Catalog/ProductValidVendor.cs
index 184caf208..1e10338c5 100644
--- a/src/Web/Grand.Web.Vendor/Validators/Catalog/ProductValidVendor.cs
+++ b/src/Web/Grand.Web.Vendor/Validators/Catalog/ProductValidVendor.cs
@@ -11,14 +11,14 @@ public class ProductValidVendor : BaseGrandValidator<IProductValidVendor>
{
public ProductValidVendor(
IEnumerable<IValidatorConsumer<IProductValidVendor>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
RuleFor(x => x).MustAsync(async (x, _, _) =>
{
var product = await productService.GetProductById(x.ProductId);
if (product == null) return true;
- return product.VendorId == workContext.CurrentVendor.Id;
+ return product.VendorId == workContextAccessor.WorkContext.CurrentVendor.Id;
}).WithMessage(translationService.GetResource("Vendor.Catalog.Products.Permissions"));
}
}
@@ -27,7 +27,7 @@ public class ProductRelatedValidVendor : BaseGrandValidator<IProductRelatedValid
{
public ProductRelatedValidVendor(
IEnumerable<IValidatorConsumer<IProductRelatedValidVendor>> validators,
- ITranslationService translationService, IProductService productService, IWorkContext workContext)
+ ITranslationService translationService, IProductService productService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
RuleFor(x => x).MustAsync(async (x, _, _) =>
@@ -36,8 +36,8 @@ public class ProductRelatedValidVendor : BaseGrandValidator<IProductRelatedValid
if (product1 == null) return true;
var product2 = await productService.GetProductById(x.ProductId2);
if (product2 == null) return true;
- return product1.VendorId == workContext.CurrentVendor.Id ||
- product2.VendorId == workContext.CurrentVendor.Id;
+ return product1.VendorId == workContextAccessor.WorkContext.CurrentVendor.Id ||
+ product2.VendorId == workContextAccessor.WorkContext.CurrentVendor.Id;
}).WithMessage(translationService.GetResource("Vendor.Catalog.Products.Permissions"));
}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Commands/Handler/Blogs/InsertBlogCommentCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Blogs/InsertBlogCommentCommandHandler.cs
index ad1637702..18429b838 100644
--- a/src/Web/Grand.Web/Commands/Handler/Blogs/InsertBlogCommentCommandHandler.cs
+++ b/src/Web/Grand.Web/Commands/Handler/Blogs/InsertBlogCommentCommandHandler.cs
@@ -17,14 +17,14 @@ public class InsertBlogCommentCommandHandler : IRequestHandler<InsertBlogComment
private readonly LanguageSettings _languageSettings;
private readonly IMessageProviderService _messageProviderService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public InsertBlogCommentCommandHandler(IBlogService blogService, IWorkContext workContext,
+ public InsertBlogCommentCommandHandler(IBlogService blogService, IWorkContextAccessor workContextAccessor,
ICustomerService customerService, IMessageProviderService messageProviderService,
LanguageSettings languageSettings, BlogSettings blogSettings)
{
_blogService = blogService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_customerService = customerService;
_messageProviderService = messageProviderService;
@@ -34,11 +34,11 @@ public class InsertBlogCommentCommandHandler : IRequestHandler<InsertBlogComment
public async Task<BlogComment> Handle(InsertBlogCommentCommand request, CancellationToken cancellationToken)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var comment = new BlogComment {
BlogPostId = request.BlogPost.Id,
CustomerId = customer.Id,
- StoreId = _workContext.CurrentStore.Id,
+ StoreId = _workContextAccessor.WorkContext.CurrentStore.Id,
CommentText = request.Model.CommentText,
BlogPostTitle = request.BlogPost.Title
};
diff --git a/src/Web/Grand.Web/Commands/Handler/Contact/ContactUsSendCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Contact/ContactUsSendCommandHandler.cs
index 62c8ac9fb..98840e0f0 100644
--- a/src/Web/Grand.Web/Commands/Handler/Contact/ContactUsSendCommandHandler.cs
+++ b/src/Web/Grand.Web/Commands/Handler/Contact/ContactUsSendCommandHandler.cs
@@ -17,15 +17,15 @@ public class ContactUsSendCommandHandler : IRequestHandler<ContactUsSendCommand,
private readonly IContactAttributeParser _contactAttributeParser;
private readonly IMessageProviderService _messageProviderService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public ContactUsSendCommandHandler(IWorkContext workContext,
+ public ContactUsSendCommandHandler(IWorkContextAccessor workContextAccessor,
IContactAttributeParser contactAttributeParser,
ITranslationService translationService,
IMessageProviderService messageProviderService,
CommonSettings commonSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_contactAttributeParser = contactAttributeParser;
_translationService = translationService;
_messageProviderService = messageProviderService;
@@ -39,9 +39,9 @@ public class ContactUsSendCommandHandler : IRequestHandler<ContactUsSendCommand,
request.Model.ContactAttribute = attributes;
request.Model.ContactAttributeInfo =
- await _contactAttributeParser.FormatAttributes(_workContext.WorkingLanguage, attributes,
- _workContext.CurrentCustomer);
- request.Model = await SendContactUs(request, _workContext.CurrentStore);
+ await _contactAttributeParser.FormatAttributes(_workContextAccessor.WorkContext.WorkingLanguage, attributes,
+ _workContextAccessor.WorkContext.CurrentCustomer);
+ request.Model = await SendContactUs(request, _workContextAccessor.WorkContext.CurrentStore);
return request.Model;
}
@@ -52,7 +52,7 @@ public class ContactUsSendCommandHandler : IRequestHandler<ContactUsSendCommand,
var body = FormatText.ConvertText(request.Model.Enquiry);
await _messageProviderService.SendContactUsMessage
- (_workContext.CurrentCustomer, store, _workContext.WorkingLanguage.Id, request.Model.Email.Trim(),
+ (_workContextAccessor.WorkContext.CurrentCustomer, store, _workContextAccessor.WorkContext.WorkingLanguage.Id, request.Model.Email.Trim(),
request.Model.FullName, subject,
body, request.Model.ContactAttributeInfo, request.Model.ContactAttribute, request.IpAddress);
diff --git a/src/Web/Grand.Web/Commands/Handler/News/InsertNewsCommentCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/News/InsertNewsCommentCommandHandler.cs
index a9666118c..d1d5d56e7 100644
--- a/src/Web/Grand.Web/Commands/Handler/News/InsertNewsCommentCommandHandler.cs
+++ b/src/Web/Grand.Web/Commands/Handler/News/InsertNewsCommentCommandHandler.cs
@@ -17,13 +17,13 @@ public class InsertNewsCommentCommandHandler : IRequestHandler<InsertNewsComment
private readonly INewsService _newsService;
private readonly NewsSettings _newsSettings;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public InsertNewsCommentCommandHandler(IWorkContext workContext, INewsService newsService,
+ public InsertNewsCommentCommandHandler(IWorkContextAccessor workContextAccessor, INewsService newsService,
ICustomerService customerService, IMessageProviderService messageProviderService, NewsSettings newsSettings,
LanguageSettings languageSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_newsService = newsService;
_customerService = customerService;
_messageProviderService = messageProviderService;
@@ -36,8 +36,8 @@ public class InsertNewsCommentCommandHandler : IRequestHandler<InsertNewsComment
{
var comment = new NewsComment {
NewsItemId = request.NewsItem.Id,
- CustomerId = _workContext.CurrentCustomer.Id,
- StoreId = _workContext.CurrentStore.Id,
+ CustomerId = _workContextAccessor.WorkContext.CurrentCustomer.Id,
+ StoreId = _workContextAccessor.WorkContext.CurrentStore.Id,
CommentTitle = request.Model.CommentTitle,
CommentText = request.Model.CommentText
};
@@ -48,7 +48,7 @@ public class InsertNewsCommentCommandHandler : IRequestHandler<InsertNewsComment
await _newsService.UpdateNews(request.NewsItem);
- await _customerService.UpdateContributions(_workContext.CurrentCustomer);
+ await _customerService.UpdateContributions(_workContextAccessor.WorkContext.CurrentCustomer);
//notify a store owner;
if (_newsSettings.NotifyAboutNewNewsComments)
diff --git a/src/Web/Grand.Web/Commands/Handler/Newsletter/SubscribeNewsletterHandler.cs b/src/Web/Grand.Web/Commands/Handler/Newsletter/SubscribeNewsletterHandler.cs
index 8a0b79383..43aaa5f75 100644
--- a/src/Web/Grand.Web/Commands/Handler/Newsletter/SubscribeNewsletterHandler.cs
+++ b/src/Web/Grand.Web/Commands/Handler/Newsletter/SubscribeNewsletterHandler.cs
@@ -17,18 +17,18 @@ public class SubscribeNewsletterHandler : IRequestHandler<SubscribeNewsletterCom
private readonly INewsletterCategoryService _newsletterCategoryService;
private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public SubscribeNewsletterHandler(INewsLetterSubscriptionService newsLetterSubscriptionService,
ITranslationService translationService,
- IMessageProviderService messageProviderService, IWorkContext workContext,
+ IMessageProviderService messageProviderService, IWorkContextAccessor workContextAccessor,
INewsletterCategoryService newsletterCategoryService)
{
_newsLetterSubscriptionService = newsLetterSubscriptionService;
_translationService = translationService;
_messageProviderService = messageProviderService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_newsletterCategoryService = newsletterCategoryService;
}
@@ -48,21 +48,21 @@ public class SubscribeNewsletterHandler : IRequestHandler<SubscribeNewsletterCom
var subscription =
await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(email,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
if (subscription != null)
{
if (request.Subscribe)
{
if (!subscription.Active)
await _messageProviderService.SendNewsLetterSubscriptionActivationMessage(subscription,
- _workContext.WorkingLanguage.Id);
+ _workContextAccessor.WorkContext.WorkingLanguage.Id);
model.Result = _translationService.GetResource("Newsletter.SubscribeEmailSent");
}
else
{
if (subscription.Active)
await _messageProviderService.SendNewsLetterSubscriptionDeactivationMessage(subscription,
- _workContext.WorkingLanguage.Id);
+ _workContextAccessor.WorkContext.WorkingLanguage.Id);
model.Result = _translationService.GetResource("Newsletter.UnsubscribeEmailSent");
}
}
@@ -71,14 +71,14 @@ public class SubscribeNewsletterHandler : IRequestHandler<SubscribeNewsletterCom
subscription = new NewsLetterSubscription {
NewsLetterSubscriptionGuid = Guid.NewGuid(),
Email = email,
- CustomerId = _workContext.CurrentCustomer.Id,
+ CustomerId = _workContextAccessor.WorkContext.CurrentCustomer.Id,
Active = false,
- StoreId = _workContext.CurrentStore.Id
+ StoreId = _workContextAccessor.WorkContext.CurrentStore.Id
};
await _newsLetterSubscriptionService.InsertNewsLetterSubscription(subscription);
await _messageProviderService.SendNewsLetterSubscriptionActivationMessage(subscription,
- _workContext.WorkingLanguage.Id);
+ _workContextAccessor.WorkContext.WorkingLanguage.Id);
model.Result = _translationService.GetResource("Newsletter.SubscribeEmailSent");
var modelCategory = await PrepareNewsletterCategory(subscription.Id);
@@ -100,12 +100,12 @@ public class SubscribeNewsletterHandler : IRequestHandler<SubscribeNewsletterCom
var model = new NewsletterCategoryModel {
NewsletterEmailId = id
};
- var categories = await _newsletterCategoryService.GetNewsletterCategoriesByStore(_workContext.CurrentStore.Id);
+ var categories = await _newsletterCategoryService.GetNewsletterCategoriesByStore(_workContextAccessor.WorkContext.CurrentStore.Id);
foreach (var item in categories)
model.NewsletterCategories.Add(new NewsletterSimpleCategory {
Id = item.Id,
- Name = item.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- Description = item.GetTranslation(x => x.Description, _workContext.WorkingLanguage.Id),
+ Name = item.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Description = item.GetTranslation(x => x.Description, _workContextAccessor.WorkContext.WorkingLanguage.Id),
Selected = item.Selected
});
return model;
diff --git a/src/Web/Grand.Web/Commands/Handler/Orders/MerchandiseReturnSubmitCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Orders/MerchandiseReturnSubmitCommandHandler.cs
index d524cf2a3..1c1d2dd3a 100644
--- a/src/Web/Grand.Web/Commands/Handler/Orders/MerchandiseReturnSubmitCommandHandler.cs
+++ b/src/Web/Grand.Web/Commands/Handler/Orders/MerchandiseReturnSubmitCommandHandler.cs
@@ -18,17 +18,17 @@ public class MerchandiseReturnSubmitCommandHandler : IRequestHandler<Merchandise
private readonly IMerchandiseReturnService _merchandiseReturnService;
private readonly IMessageProviderService _messageProviderService;
private readonly IProductService _productService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public MerchandiseReturnSubmitCommandHandler(IWorkContext workContext,
+ public MerchandiseReturnSubmitCommandHandler(IWorkContextAccessor workContextAccessor,
IProductService productService,
IMerchandiseReturnService merchandiseReturnService,
IMessageProviderService messageProviderService,
IGroupService groupService,
LanguageSettings languageSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_productService = productService;
_merchandiseReturnService = merchandiseReturnService;
_messageProviderService = messageProviderService;
@@ -40,12 +40,12 @@ public class MerchandiseReturnSubmitCommandHandler : IRequestHandler<Merchandise
MerchandiseReturnSubmitCommand request, CancellationToken cancellationToken)
{
var rr = new MerchandiseReturn {
- StoreId = _workContext.CurrentStore.Id,
+ StoreId = _workContextAccessor.WorkContext.CurrentStore.Id,
OrderId = request.Order.Id,
- CustomerId = _workContext.CurrentCustomer.Id,
- OwnerId = await _groupService.IsOwner(_workContext.CurrentCustomer)
- ? _workContext.CurrentCustomer.Id
- : _workContext.CurrentCustomer.OwnerId,
+ CustomerId = _workContextAccessor.WorkContext.CurrentCustomer.Id,
+ OwnerId = await _groupService.IsOwner(_workContextAccessor.WorkContext.CurrentCustomer)
+ ? _workContextAccessor.WorkContext.CurrentCustomer.Id
+ : _workContextAccessor.WorkContext.CurrentCustomer.OwnerId,
SeId = request.Order.SeId,
CustomerComments = request.Model.Comments,
StaffNotes = string.Empty,
@@ -71,10 +71,10 @@ public class MerchandiseReturnSubmitCommandHandler : IRequestHandler<Merchandise
var rra = await _merchandiseReturnService.GetMerchandiseReturnActionById(rraId);
rr.MerchandiseReturnItems.Add(new MerchandiseReturnItem {
RequestedAction = rra != null
- ? rra.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id)
+ ? rra.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id)
: "not available",
ReasonForReturn = rrr != null
- ? rrr.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id)
+ ? rrr.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id)
: "not available",
Quantity = quantity.Value,
OrderItemId = orderItem.Id
diff --git a/src/Web/Grand.Web/Commands/Handler/Vendors/ContactVendorCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Vendors/ContactVendorCommandHandler.cs
index 2821e426a..dcf97ca7c 100644
--- a/src/Web/Grand.Web/Commands/Handler/Vendors/ContactVendorCommandHandler.cs
+++ b/src/Web/Grand.Web/Commands/Handler/Vendors/ContactVendorCommandHandler.cs
@@ -14,13 +14,13 @@ public class ContactVendorCommandHandler : IRequestHandler<ContactVendorSendComm
private readonly CommonSettings _commonSettings;
private readonly IMessageProviderService _messageProviderService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public ContactVendorCommandHandler(IMessageProviderService messageProviderService, IWorkContext workContext,
+ public ContactVendorCommandHandler(IMessageProviderService messageProviderService, IWorkContextAccessor workContextAccessor,
ITranslationService translationService, CommonSettings commonSettings)
{
_messageProviderService = messageProviderService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_translationService = translationService;
_commonSettings = commonSettings;
}
@@ -30,8 +30,8 @@ public class ContactVendorCommandHandler : IRequestHandler<ContactVendorSendComm
var subject = _commonSettings.SubjectFieldOnContactUsForm ? request.Model.Subject : null;
var body = FormatText.ConvertText(request.Model.Enquiry);
- await _messageProviderService.SendContactVendorMessage(_workContext.CurrentCustomer, request.Store,
- request.Vendor, _workContext.WorkingLanguage.Id,
+ await _messageProviderService.SendContactVendorMessage(_workContextAccessor.WorkContext.CurrentCustomer, request.Store,
+ request.Vendor, _workContextAccessor.WorkContext.WorkingLanguage.Id,
request.Model.Email.Trim(), request.Model.FullName, subject, body, request.IpAddress);
request.Model.SuccessfullySent = true;
diff --git a/src/Web/Grand.Web/Commands/Handler/Vendors/InsertVendorReviewCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Vendors/InsertVendorReviewCommandHandler.cs
index a7643eb73..a6edeb7f0 100644
--- a/src/Web/Grand.Web/Commands/Handler/Vendors/InsertVendorReviewCommandHandler.cs
+++ b/src/Web/Grand.Web/Commands/Handler/Vendors/InsertVendorReviewCommandHandler.cs
@@ -16,15 +16,15 @@ public class InsertVendorReviewCommandHandler : IRequestHandler<InsertVendorRevi
private readonly IMessageProviderService _messageProviderService;
private readonly IVendorService _vendorService;
private readonly VendorSettings _vendorSettings;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public InsertVendorReviewCommandHandler(IVendorService vendorService, IWorkContext workContext,
+ public InsertVendorReviewCommandHandler(IVendorService vendorService, IWorkContextAccessor workContextAccessor,
ICustomerService customerService, IMessageProviderService messageProviderService,
LanguageSettings languageSettings, VendorSettings vendorSettings)
{
_vendorService = vendorService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_customerService = customerService;
_messageProviderService = messageProviderService;
_languageSettings = languageSettings;
@@ -41,7 +41,7 @@ public class InsertVendorReviewCommandHandler : IRequestHandler<InsertVendorRevi
var vendorReview = new VendorReview {
VendorId = request.Vendor.Id,
- CustomerId = _workContext.CurrentCustomer.Id,
+ CustomerId = _workContextAccessor.WorkContext.CurrentCustomer.Id,
Title = request.Model.AddVendorReview.Title,
ReviewText = request.Model.AddVendorReview.ReviewText,
Rating = rating,
@@ -51,8 +51,8 @@ public class InsertVendorReviewCommandHandler : IRequestHandler<InsertVendorRevi
};
await _vendorService.InsertVendorReview(vendorReview);
- if (!_workContext.CurrentCustomer.HasContributions)
- await _customerService.UpdateContributions(_workContext.CurrentCustomer);
+ if (!_workContextAccessor.WorkContext.CurrentCustomer.HasContributions)
+ await _customerService.UpdateContributions(_workContextAccessor.WorkContext.CurrentCustomer);
//update vendor totals
await _vendorService.UpdateVendorReviewTotals(request.Vendor);
diff --git a/src/Web/Grand.Web/Components/CategoryFeaturedProducts.cs b/src/Web/Grand.Web/Components/CategoryFeaturedProducts.cs
index 51ce623ce..58c5f2f86 100644
--- a/src/Web/Grand.Web/Components/CategoryFeaturedProducts.cs
+++ b/src/Web/Grand.Web/Components/CategoryFeaturedProducts.cs
@@ -12,10 +12,10 @@ public class CategoryFeaturedProductsViewComponent : BaseViewComponent
public CategoryFeaturedProductsViewComponent(
IMediator mediator,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
#endregion
@@ -25,9 +25,9 @@ public class CategoryFeaturedProductsViewComponent : BaseViewComponent
public async Task<IViewComponentResult> InvokeAsync()
{
var model = await _mediator.Send(new GetCategoryFeaturedProducts {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return !model.Any() ? Content("") : View(model);
@@ -38,7 +38,7 @@ public class CategoryFeaturedProductsViewComponent : BaseViewComponent
#region Fields
private readonly IMediator _mediator;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
#endregion
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Components/CategoryNavigation.cs b/src/Web/Grand.Web/Components/CategoryNavigation.cs
index a8ab57743..67ed3e2c0 100644
--- a/src/Web/Grand.Web/Components/CategoryNavigation.cs
+++ b/src/Web/Grand.Web/Components/CategoryNavigation.cs
@@ -9,22 +9,22 @@ namespace Grand.Web.Components;
public class CategoryNavigationViewComponent : BaseViewComponent
{
private readonly IMediator _mediator;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public CategoryNavigationViewComponent(
IMediator mediator,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<IViewComponentResult> InvokeAsync(string currentCategoryId, string currentProductId)
{
var model = await _mediator.Send(new GetCategoryNavigation {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
CurrentCategoryId = currentCategoryId,
CurrentProductId = currentProductId
});
diff --git a/src/Web/Grand.Web/Components/CollectionFeaturedProducts.cs b/src/Web/Grand.Web/Components/CollectionFeaturedProducts.cs
index f4a6afcb2..8cbef6572 100644
--- a/src/Web/Grand.Web/Components/CollectionFeaturedProducts.cs
+++ b/src/Web/Grand.Web/Components/CollectionFeaturedProducts.cs
@@ -10,10 +10,10 @@ public class CollectionFeaturedProductsViewComponent : BaseViewComponent
{
#region Constructors
- public CollectionFeaturedProductsViewComponent(IMediator mediator, IWorkContext workContext)
+ public CollectionFeaturedProductsViewComponent(IMediator mediator, IWorkContextAccessor workContextAccessor)
{
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
#endregion
@@ -23,9 +23,9 @@ public class CollectionFeaturedProductsViewComponent : BaseViewComponent
public async Task<IViewComponentResult> InvokeAsync()
{
var model = await _mediator.Send(new GetCollectionFeaturedProducts {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return !model.Any() ? Content("") : View(model);
@@ -36,7 +36,7 @@ public class CollectionFeaturedProductsViewComponent : BaseViewComponent
#region Fields
private readonly IMediator _mediator;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
#endregion
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Components/CollectionNavigation.cs b/src/Web/Grand.Web/Components/CollectionNavigation.cs
index 2d4578ed5..965737f76 100644
--- a/src/Web/Grand.Web/Components/CollectionNavigation.cs
+++ b/src/Web/Grand.Web/Components/CollectionNavigation.cs
@@ -11,15 +11,15 @@ public class CollectionNavigationViewComponent : BaseViewComponent
{
private readonly CatalogSettings _catalogSettings;
private readonly IMediator _mediator;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public CollectionNavigationViewComponent(
IMediator mediator,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
CatalogSettings catalogSettings)
{
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_catalogSettings = catalogSettings;
}
@@ -30,9 +30,9 @@ public class CollectionNavigationViewComponent : BaseViewComponent
var model = await _mediator.Send(new GetCollectionNavigation {
CurrentCollectionId = currentCollectionId,
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return !model.Collections.Any() ? Content("") : View(model);
diff --git a/src/Web/Grand.Web/Components/CrossSellProducts.cs b/src/Web/Grand.Web/Components/CrossSellProducts.cs
index b23ac5872..a8dd15cf9 100644
--- a/src/Web/Grand.Web/Components/CrossSellProducts.cs
+++ b/src/Web/Grand.Web/Components/CrossSellProducts.cs
@@ -15,13 +15,13 @@ public class CrossSellProductsViewComponent : BaseViewComponent
public CrossSellProductsViewComponent(
IProductService productService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator,
CatalogSettings catalogSettings,
ShoppingCartSettings shoppingCartSettings)
{
_productService = productService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_catalogSettings = catalogSettings;
_shoppingCartSettings = shoppingCartSettings;
@@ -36,9 +36,9 @@ public class CrossSellProductsViewComponent : BaseViewComponent
if (_shoppingCartSettings.CrossSellsNumber == 0)
return Content("");
- var cart = _workContext.CurrentCustomer.ShoppingCartItems
+ var cart = _workContextAccessor.WorkContext.CurrentCustomer.ShoppingCartItems
.Where(sci => sci.ShoppingCartTypeId == ShoppingCartType.ShoppingCart)
- .LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, _workContext.CurrentStore.Id)
+ .LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, _workContextAccessor.WorkContext.CurrentStore.Id)
.ToList();
var products =
@@ -62,7 +62,7 @@ public class CrossSellProductsViewComponent : BaseViewComponent
#region Fields
private readonly IProductService _productService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
private readonly CatalogSettings _catalogSettings;
diff --git a/src/Web/Grand.Web/Components/CustomerNavigation.cs b/src/Web/Grand.Web/Components/CustomerNavigation.cs
index f056fdda3..8e908dbf7 100644
--- a/src/Web/Grand.Web/Components/CustomerNavigation.cs
+++ b/src/Web/Grand.Web/Components/CustomerNavigation.cs
@@ -9,23 +9,23 @@ namespace Grand.Web.Components;
public class CustomerNavigationViewComponent : BaseViewComponent
{
private readonly IMediator _mediator;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public CustomerNavigationViewComponent(IMediator mediator,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<IViewComponentResult> InvokeAsync(int selectedTabId = 0)
{
var model = await _mediator.Send(new GetNavigation {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
SelectedTabId = selectedTabId,
- Store = _workContext.CurrentStore,
- Vendor = _workContext.CurrentVendor
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ Vendor = _workContextAccessor.WorkContext.CurrentVendor
});
return View(model);
}
diff --git a/src/Web/Grand.Web/Components/CustomerRecommendedProducts.cs b/src/Web/Grand.Web/Components/CustomerRecommendedProducts.cs
index 80ad296e2..7c5e07db0 100644
--- a/src/Web/Grand.Web/Components/CustomerRecommendedProducts.cs
+++ b/src/Web/Grand.Web/Components/CustomerRecommendedProducts.cs
@@ -14,11 +14,11 @@ public class CustomerRecommendedProductsViewComponent : BaseViewComponent
#region Constructors
public CustomerRecommendedProductsViewComponent(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator,
CatalogSettings catalogSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_catalogSettings = catalogSettings;
}
@@ -33,8 +33,8 @@ public class CustomerRecommendedProductsViewComponent : BaseViewComponent
return Content("");
var products = await _mediator.Send(new GetRecommendedProductsQuery {
- CustomerGroupIds = _workContext.CurrentCustomer.GetCustomerGroupIds(),
- StoreId = _workContext.CurrentStore.Id
+ CustomerGroupIds = _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds(),
+ StoreId = _workContextAccessor.WorkContext.CurrentStore.Id
});
if (!products.Any())
@@ -54,7 +54,7 @@ public class CustomerRecommendedProductsViewComponent : BaseViewComponent
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
private readonly CatalogSettings _catalogSettings;
diff --git a/src/Web/Grand.Web/Components/EmailWishlist.cs b/src/Web/Grand.Web/Components/EmailWishlist.cs
index 2ce6aa813..5b3ec74b1 100644
--- a/src/Web/Grand.Web/Components/EmailWishlist.cs
+++ b/src/Web/Grand.Web/Components/EmailWishlist.cs
@@ -16,17 +16,17 @@ public class EmailWishlistViewComponent : BaseViewComponent
private readonly IPermissionService _permissionService;
private readonly IShoppingCartService _shoppingCartService;
private readonly ShoppingCartSettings _shoppingCartSettings;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public EmailWishlistViewComponent(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IShoppingCartService shoppingCartService,
IPermissionService permissionService,
ShoppingCartSettings shoppingCartSettings,
CaptchaSettings captchaSettings
)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_shoppingCartService = shoppingCartService;
_permissionService = permissionService;
_shoppingCartSettings = shoppingCartSettings;
@@ -39,13 +39,13 @@ public class EmailWishlistViewComponent : BaseViewComponent
!_shoppingCartSettings.EmailWishlistEnabled)
return Content("");
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, ShoppingCartType.Wishlist);
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id, ShoppingCartType.Wishlist);
if (!cart.Any())
return Content("");
var model = new WishlistEmailAFriendModel {
- YourEmailAddress = _workContext.CurrentCustomer.Email,
+ YourEmailAddress = _workContextAccessor.WorkContext.CurrentCustomer.Email,
DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnEmailWishlistToFriendPage
};
return View(model);
diff --git a/src/Web/Grand.Web/Components/EstimateShipping.cs b/src/Web/Grand.Web/Components/EstimateShipping.cs
index 879788ca7..8ae17e048 100644
--- a/src/Web/Grand.Web/Components/EstimateShipping.cs
+++ b/src/Web/Grand.Web/Components/EstimateShipping.cs
@@ -12,27 +12,27 @@ public class EstimateShippingViewComponent : BaseViewComponent
{
private readonly IMediator _mediator;
private readonly IShoppingCartService _shoppingCartService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public EstimateShippingViewComponent(IMediator mediator, IShoppingCartService shoppingCartService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_mediator = mediator;
_shoppingCartService = shoppingCartService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<IViewComponentResult> InvokeAsync()
{
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.ShoppingCart);
var model = await _mediator.Send(new GetEstimateShipping {
Cart = cart,
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return !model.Enabled ? Content("") : View(model);
}
diff --git a/src/Web/Grand.Web/Components/ExternalMethods.cs b/src/Web/Grand.Web/Components/ExternalMethods.cs
index 0bdff3e1b..663123ca4 100644
--- a/src/Web/Grand.Web/Components/ExternalMethods.cs
+++ b/src/Web/Grand.Web/Components/ExternalMethods.cs
@@ -9,20 +9,20 @@ namespace Grand.Web.Components;
public class ExternalMethodsViewComponent : BaseViewComponent
{
private readonly IExternalAuthenticationService _externalAuthenticationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public ExternalMethodsViewComponent(
IExternalAuthenticationService externalAuthenticationService,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_externalAuthenticationService = externalAuthenticationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var models = _externalAuthenticationService
- .LoadActiveAuthenticationProviders(_workContext.CurrentCustomer, _workContext.CurrentStore);
+ .LoadActiveAuthenticationProviders(_workContextAccessor.WorkContext.CurrentCustomer, _workContextAccessor.WorkContext.CurrentStore);
var model = new List<ExternalAuthenticationMethodModel>();
foreach (var item in models)
diff --git a/src/Web/Grand.Web/Components/Footer.cs b/src/Web/Grand.Web/Components/Footer.cs
index 5dec1300c..c2b4bf72a 100644
--- a/src/Web/Grand.Web/Components/Footer.cs
+++ b/src/Web/Grand.Web/Components/Footer.cs
@@ -29,10 +29,10 @@ public class FooterViewComponent : BaseViewComponent
private readonly StoreInformationSettings _storeInformationSettings;
private readonly VendorSettings _vendorSettings;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public FooterViewComponent(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IPageService pageService,
IPermissionService permissionService,
StoreInformationSettings storeInformationSettings,
@@ -43,7 +43,7 @@ public class FooterViewComponent : BaseViewComponent
VendorSettings vendorSettings,
CommonSettings commonSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_pageService = pageService;
_permissionService = permissionService;
@@ -65,23 +65,23 @@ public class FooterViewComponent : BaseViewComponent
private async Task<FooterModel> PrepareFooter()
{
var now = DateTime.UtcNow;
- var pageModel = (await _pageService.GetAllPages(_workContext.CurrentStore.Id))
+ var pageModel = (await _pageService.GetAllPages(_workContextAccessor.WorkContext.CurrentStore.Id))
.Where(t => (t.IncludeInFooterRow1 || t.IncludeInFooterRow2 || t.IncludeInFooterRow3) && t.Published &&
(!t.StartDateUtc.HasValue || t.StartDateUtc < now) &&
(!t.EndDateUtc.HasValue || t.EndDateUtc > now))
.Select(t => new FooterModel.FooterPageModel {
Id = t.Id,
- Name = t.GetTranslation(x => x.Title, _workContext.WorkingLanguage.Id),
- SeName = t.GetSeName(_workContext.WorkingLanguage.Id),
+ Name = t.GetTranslation(x => x.Title, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ SeName = t.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id),
IncludeInFooterRow1 = t.IncludeInFooterRow1,
IncludeInFooterRow2 = t.IncludeInFooterRow2,
IncludeInFooterRow3 = t.IncludeInFooterRow3
}).ToList();
//model
- var currentstore = _workContext.CurrentStore;
+ var currentstore = _workContextAccessor.WorkContext.CurrentStore;
var model = new FooterModel {
- StoreName = currentstore.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
+ StoreName = currentstore.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
CompanyName = currentstore.CompanyName,
CompanyEmail = currentstore.CompanyEmail,
CompanyAddress = currentstore.CompanyAddress,
@@ -91,7 +91,7 @@ public class FooterViewComponent : BaseViewComponent
WishlistEnabled = await _permissionService.Authorize(StandardPermission.EnableWishlist),
ShoppingCartEnabled = await _permissionService.Authorize(StandardPermission.EnableShoppingCart),
SitemapEnabled = _commonSettings.SitemapEnabled,
- WorkingLanguageId = _workContext.WorkingLanguage.Id,
+ WorkingLanguageId = _workContextAccessor.WorkContext.WorkingLanguage.Id,
FacebookLink = _storeInformationSettings.FacebookLink,
TwitterLink = _storeInformationSettings.TwitterLink,
YoutubeLink = _storeInformationSettings.YoutubeLink,
@@ -104,7 +104,7 @@ public class FooterViewComponent : BaseViewComponent
RecentlyViewedProductsEnabled = _catalogSettings.RecentlyViewedProductsEnabled,
RecommendedProductsEnabled = _catalogSettings.RecommendedProductsEnabled,
NewProductsEnabled = _catalogSettings.NewProductsEnabled,
- InclTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax,
+ InclTax = _workContextAccessor.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax,
AllowCustomersToApplyForVendorAccount = _vendorSettings.AllowCustomersToApplyForVendorAccount,
Pages = pageModel
};
diff --git a/src/Web/Grand.Web/Components/GetCoordinate.cs b/src/Web/Grand.Web/Components/GetCoordinate.cs
index b64e48375..88ef6254a 100644
--- a/src/Web/Grand.Web/Components/GetCoordinate.cs
+++ b/src/Web/Grand.Web/Components/GetCoordinate.cs
@@ -9,12 +9,12 @@ namespace Grand.Web.Components;
public class GetCoordinateViewComponent : BaseViewComponent
{
private readonly CustomerSettings _customerSettings;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public GetCoordinateViewComponent(CustomerSettings customerSettings, IWorkContext workContext)
+ public GetCoordinateViewComponent(CustomerSettings customerSettings, IWorkContextAccessor workContextAccessor)
{
_customerSettings = customerSettings;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public IViewComponentResult Invoke()
@@ -22,12 +22,12 @@ public class GetCoordinateViewComponent : BaseViewComponent
if (!_customerSettings.GeoEnabled)
return Content("");
- if (_workContext.CurrentCustomer.Coordinates == null)
+ if (_workContextAccessor.WorkContext.CurrentCustomer.Coordinates == null)
return View(new LocationModel());
var model = new LocationModel {
- Longitude = _workContext.CurrentCustomer.Coordinates.X,
- Latitude = _workContext.CurrentCustomer.Coordinates.Y
+ Longitude = _workContextAccessor.WorkContext.CurrentCustomer.Coordinates.X,
+ Latitude = _workContextAccessor.WorkContext.CurrentCustomer.Coordinates.Y
};
return View(model);
}
diff --git a/src/Web/Grand.Web/Components/HomePageBestSellers.cs b/src/Web/Grand.Web/Components/HomePageBestSellers.cs
index 580faa484..8d7fb846e 100644
--- a/src/Web/Grand.Web/Components/HomePageBestSellers.cs
+++ b/src/Web/Grand.Web/Components/HomePageBestSellers.cs
@@ -19,14 +19,14 @@ public class HomePageBestSellersViewComponent : BaseViewComponent
public HomePageBestSellersViewComponent(
IOrderReportService orderReportService,
ICacheBase cacheBase,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IProductService productService,
IMediator mediator,
CatalogSettings catalogSettings)
{
_orderReportService = orderReportService;
_cacheBase = cacheBase;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_productService = productService;
_mediator = mediator;
_catalogSettings = catalogSettings;
@@ -50,11 +50,11 @@ public class HomePageBestSellersViewComponent : BaseViewComponent
? -_catalogSettings.PeriodBestsellers
: -12);
var report = await _cacheBase.GetAsync(
- string.Format(CacheKeyConst.HOMEPAGE_BESTSELLERS_IDS_KEY, _workContext.CurrentStore.Id), async () =>
+ string.Format(CacheKeyConst.HOMEPAGE_BESTSELLERS_IDS_KEY, _workContextAccessor.WorkContext.CurrentStore.Id), async () =>
await _orderReportService.BestSellersReport(
createdFromUtc: fromdate,
ps: PaymentStatus.Paid,
- storeId: _workContext.CurrentStore.Id,
+ storeId: _workContextAccessor.WorkContext.CurrentStore.Id,
pageSize: _catalogSettings.NumberOfBestsellersOnHomepage));
productIds = report.Select(x => x.ProductId).ToList();
@@ -85,7 +85,7 @@ public class HomePageBestSellersViewComponent : BaseViewComponent
private readonly IOrderReportService _orderReportService;
private readonly ICacheBase _cacheBase;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IProductService _productService;
private readonly IMediator _mediator;
diff --git a/src/Web/Grand.Web/Components/HomePageBrands.cs b/src/Web/Grand.Web/Components/HomePageBrands.cs
index ab0c67a43..1cf269c00 100644
--- a/src/Web/Grand.Web/Components/HomePageBrands.cs
+++ b/src/Web/Grand.Web/Components/HomePageBrands.cs
@@ -9,22 +9,22 @@ namespace Grand.Web.Components;
public class HomePageBrandsViewComponent : BaseViewComponent
{
private readonly IMediator _mediator;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public HomePageBrandsViewComponent(
IMediator mediator,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var model = await _mediator.Send(new GetHomepageBrands {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return !model.Any() ? Content("") : View(model);
diff --git a/src/Web/Grand.Web/Components/HomePageCategories.cs b/src/Web/Grand.Web/Components/HomePageCategories.cs
index 787f692a7..16e4b251b 100644
--- a/src/Web/Grand.Web/Components/HomePageCategories.cs
+++ b/src/Web/Grand.Web/Components/HomePageCategories.cs
@@ -12,10 +12,10 @@ public class HomePageCategoriesViewComponent : BaseViewComponent
public HomePageCategoriesViewComponent(
IMediator mediator,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
#endregion
@@ -25,9 +25,9 @@ public class HomePageCategoriesViewComponent : BaseViewComponent
public async Task<IViewComponentResult> InvokeAsync()
{
var model = await _mediator.Send(new GetHomepageCategory {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return !model.Any() ? Content("") : View(model);
@@ -38,7 +38,7 @@ public class HomePageCategoriesViewComponent : BaseViewComponent
#region Fields
private readonly IMediator _mediator;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
#endregion
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Components/HomePageCollections.cs b/src/Web/Grand.Web/Components/HomePageCollections.cs
index 9019ebcf0..a300f6092 100644
--- a/src/Web/Grand.Web/Components/HomePageCollections.cs
+++ b/src/Web/Grand.Web/Components/HomePageCollections.cs
@@ -9,22 +9,22 @@ namespace Grand.Web.Components;
public class HomePageCollectionsViewComponent : BaseViewComponent
{
private readonly IMediator _mediator;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public HomePageCollectionsViewComponent(
IMediator mediator,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var model = await _mediator.Send(new GetHomepageCollections {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return !model.Any() ? Content("") : View(model);
diff --git a/src/Web/Grand.Web/Components/HomePageNewProducts.cs b/src/Web/Grand.Web/Components/HomePageNewProducts.cs
index faed1c9ef..3399fc557 100644
--- a/src/Web/Grand.Web/Components/HomePageNewProducts.cs
+++ b/src/Web/Grand.Web/Components/HomePageNewProducts.cs
@@ -13,11 +13,11 @@ public class HomePageNewProductsViewComponent : BaseViewComponent
#region Constructors
public HomePageNewProductsViewComponent(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator,
CatalogSettings catalogSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_catalogSettings = catalogSettings;
}
@@ -32,8 +32,8 @@ public class HomePageNewProductsViewComponent : BaseViewComponent
return Content("");
var products = (await _mediator.Send(new GetSearchProductsQuery {
- Customer = _workContext.CurrentCustomer,
- StoreId = _workContext.CurrentStore.Id,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ StoreId = _workContextAccessor.WorkContext.CurrentStore.Id,
VisibleIndividuallyOnly = true,
MarkedAsNewOnly = true,
OrderBy = ProductSortingEnum.CreatedOn,
@@ -58,7 +58,7 @@ public class HomePageNewProductsViewComponent : BaseViewComponent
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
private readonly CatalogSettings _catalogSettings;
diff --git a/src/Web/Grand.Web/Components/KnowledgebaseCategories.cs b/src/Web/Grand.Web/Components/KnowledgebaseCategories.cs
index 44a2d5fad..d411e2528 100644
--- a/src/Web/Grand.Web/Components/KnowledgebaseCategories.cs
+++ b/src/Web/Grand.Web/Components/KnowledgebaseCategories.cs
@@ -12,13 +12,13 @@ public class KnowledgebaseCategories : BaseViewComponent
{
private readonly IKnowledgebaseService _knowledgebaseService;
private readonly KnowledgebaseSettings _knowledgebaseSettings;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public KnowledgebaseCategories(IKnowledgebaseService knowledgebaseService, IWorkContext workContext,
+ public KnowledgebaseCategories(IKnowledgebaseService knowledgebaseService, IWorkContextAccessor workContextAccessor,
KnowledgebaseSettings knowledgebaseSettings)
{
_knowledgebaseService = knowledgebaseService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_knowledgebaseSettings = knowledgebaseSettings;
}
@@ -34,10 +34,10 @@ public class KnowledgebaseCategories : BaseViewComponent
if (!string.IsNullOrEmpty(category.ParentCategoryId)) continue;
var newNode = new KnowledgebaseCategoryModel {
Id = category.Id,
- Name = category.GetTranslation(y => y.Name, _workContext.WorkingLanguage.Id),
+ Name = category.GetTranslation(y => y.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
Children = new List<KnowledgebaseCategoryModel>(),
IsCurrent = model.CurrentCategoryId == category.Id,
- SeName = category.GetTranslation(y => y.SeName, _workContext.WorkingLanguage.Id)
+ SeName = category.GetTranslation(y => y.SeName, _workContextAccessor.WorkContext.WorkingLanguage.Id)
};
FillChildNodes(newNode, categories, model.CurrentCategoryId);
@@ -56,10 +56,10 @@ public class KnowledgebaseCategories : BaseViewComponent
{
var newNode = new KnowledgebaseCategoryModel {
Id = child.Id,
- Name = child.GetTranslation(y => y.Name, _workContext.WorkingLanguage.Id),
+ Name = child.GetTranslation(y => y.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
Children = new List<KnowledgebaseCategoryModel>(),
IsCurrent = currentCategoryId == child.Id,
- SeName = child.GetTranslation(y => y.SeName, _workContext.WorkingLanguage.Id),
+ SeName = child.GetTranslation(y => y.SeName, _workContextAccessor.WorkContext.WorkingLanguage.Id),
Parent = parentNode
};
diff --git a/src/Web/Grand.Web/Components/KnowledgebaseHomepageArticles.cs b/src/Web/Grand.Web/Components/KnowledgebaseHomepageArticles.cs
index 67a8f2c91..7ff28b13e 100644
--- a/src/Web/Grand.Web/Components/KnowledgebaseHomepageArticles.cs
+++ b/src/Web/Grand.Web/Components/KnowledgebaseHomepageArticles.cs
@@ -12,13 +12,13 @@ public class KnowledgebaseHomepageArticles : BaseViewComponent
{
private readonly IKnowledgebaseService _knowledgebaseService;
private readonly KnowledgebaseSettings _knowledgebaseSettings;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public KnowledgebaseHomepageArticles(IKnowledgebaseService knowledgebaseService, IWorkContext workContext,
+ public KnowledgebaseHomepageArticles(IKnowledgebaseService knowledgebaseService, IWorkContextAccessor workContextAccessor,
KnowledgebaseSettings knowledgebaseSettings)
{
_knowledgebaseService = knowledgebaseService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_knowledgebaseSettings = knowledgebaseSettings;
}
@@ -33,8 +33,8 @@ public class KnowledgebaseHomepageArticles : BaseViewComponent
{
var a = new KnowledgebaseItemModel {
Id = article.Id,
- Name = article.GetTranslation(y => y.Name, _workContext.WorkingLanguage.Id),
- SeName = article.GetTranslation(y => y.SeName, _workContext.WorkingLanguage.Id),
+ Name = article.GetTranslation(y => y.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ SeName = article.GetTranslation(y => y.SeName, _workContextAccessor.WorkContext.WorkingLanguage.Id),
IsArticle = true
};
diff --git a/src/Web/Grand.Web/Components/Menu.cs b/src/Web/Grand.Web/Components/Menu.cs
index d5f83b4f5..62d01fe4c 100644
--- a/src/Web/Grand.Web/Components/Menu.cs
+++ b/src/Web/Grand.Web/Components/Menu.cs
@@ -12,28 +12,28 @@ public class MenuViewComponent : BaseViewComponent
{
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public MenuViewComponent(
IMediator mediator,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IPermissionService permissionService)
{
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_permissionService = permissionService;
}
public async Task<IViewComponentResult> InvokeAsync()
{
if (!await _permissionService.Authorize(StandardPermission.PublicStoreAllowNavigation,
- _workContext.CurrentCustomer))
+ _workContextAccessor.WorkContext.CurrentCustomer))
return Content("");
var model = await _mediator.Send(new GetMenu {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return View(model);
diff --git a/src/Web/Grand.Web/Components/PersonalizedProducts.cs b/src/Web/Grand.Web/Components/PersonalizedProducts.cs
index 0db14a629..17e314b77 100644
--- a/src/Web/Grand.Web/Components/PersonalizedProducts.cs
+++ b/src/Web/Grand.Web/Components/PersonalizedProducts.cs
@@ -13,11 +13,11 @@ public class PersonalizedProductsViewComponent : BaseViewComponent
#region Constructors
public PersonalizedProductsViewComponent(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator,
CatalogSettings catalogSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_catalogSettings = catalogSettings;
}
@@ -32,7 +32,7 @@ public class PersonalizedProductsViewComponent : BaseViewComponent
return Content("");
var products = await _mediator.Send(new GetPersonalizedProductsQuery {
- CustomerId = _workContext.CurrentCustomer.Id, ProductsNumber = _catalogSettings.PersonalizedProductsNumber
+ CustomerId = _workContextAccessor.WorkContext.CurrentCustomer.Id, ProductsNumber = _catalogSettings.PersonalizedProductsNumber
});
if (!products.Any())
@@ -52,7 +52,7 @@ public class PersonalizedProductsViewComponent : BaseViewComponent
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
private readonly CatalogSettings _catalogSettings;
diff --git a/src/Web/Grand.Web/Components/PopularProductTags.cs b/src/Web/Grand.Web/Components/PopularProductTags.cs
index 45702a8c5..f9c4f8b81 100644
--- a/src/Web/Grand.Web/Components/PopularProductTags.cs
+++ b/src/Web/Grand.Web/Components/PopularProductTags.cs
@@ -9,19 +9,19 @@ namespace Grand.Web.Components;
public class PopularProductTagsViewComponent : BaseViewComponent
{
private readonly IMediator _mediator;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public PopularProductTagsViewComponent(IMediator mediator, IWorkContext workContext)
+ public PopularProductTagsViewComponent(IMediator mediator, IWorkContextAccessor workContextAccessor)
{
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var model = await _mediator.Send(new GetPopularProductTags {
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return !model.Tags.Any() ? Content("") : View(model);
}
diff --git a/src/Web/Grand.Web/Components/ProductEmailAFriend.cs b/src/Web/Grand.Web/Components/ProductEmailAFriend.cs
index b4e8626ac..3e7ab267d 100644
--- a/src/Web/Grand.Web/Components/ProductEmailAFriend.cs
+++ b/src/Web/Grand.Web/Components/ProductEmailAFriend.cs
@@ -15,12 +15,12 @@ public class ProductEmailAFriendViewComponent : BaseViewComponent
public ProductEmailAFriendViewComponent(
IProductService productService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
CatalogSettings catalogSettings,
CaptchaSettings captchaSettings)
{
_productService = productService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_catalogSettings = catalogSettings;
_captchaSettings = captchaSettings;
}
@@ -37,9 +37,9 @@ public class ProductEmailAFriendViewComponent : BaseViewComponent
var model = new ProductEmailAFriendModel {
ProductId = product.Id,
- ProductName = product.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- ProductSeName = product.GetSeName(_workContext.WorkingLanguage.Id),
- YourEmailAddress = _workContext.CurrentCustomer.Email,
+ ProductName = product.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ ProductSeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id),
+ YourEmailAddress = _workContextAccessor.WorkContext.CurrentCustomer.Email,
DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnEmailProductToFriendPage
};
@@ -51,7 +51,7 @@ public class ProductEmailAFriendViewComponent : BaseViewComponent
#region Fields
private readonly IProductService _productService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly CatalogSettings _catalogSettings;
private readonly CaptchaSettings _captchaSettings;
diff --git a/src/Web/Grand.Web/Components/ProductReviews.cs b/src/Web/Grand.Web/Components/ProductReviews.cs
index 459c482e4..1b006d0be 100644
--- a/src/Web/Grand.Web/Components/ProductReviews.cs
+++ b/src/Web/Grand.Web/Components/ProductReviews.cs
@@ -15,11 +15,11 @@ public class ProductReviewsViewComponent : BaseViewComponent
public ProductReviewsViewComponent(
IProductService productService,
IMediator mediator,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
CatalogSettings catalogSettings)
{
_productService = productService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_catalogSettings = catalogSettings;
}
@@ -35,10 +35,10 @@ public class ProductReviewsViewComponent : BaseViewComponent
return Content("");
var model = await _mediator.Send(new GetProductReviews {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
Product = product,
- Store = _workContext.CurrentStore,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Size = _catalogSettings.NumberOfReview
});
@@ -51,7 +51,7 @@ public class ProductReviewsViewComponent : BaseViewComponent
private readonly IProductService _productService;
private readonly IMediator _mediator;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly CatalogSettings _catalogSettings;
#endregion
diff --git a/src/Web/Grand.Web/Components/ProductsAlsoPurchased.cs b/src/Web/Grand.Web/Components/ProductsAlsoPurchased.cs
index a617ac475..ce91e3fe2 100644
--- a/src/Web/Grand.Web/Components/ProductsAlsoPurchased.cs
+++ b/src/Web/Grand.Web/Components/ProductsAlsoPurchased.cs
@@ -20,7 +20,7 @@ public class ProductsAlsoPurchasedViewComponent : BaseViewComponent
IMediator mediator,
ICacheBase cacheBase,
IOrderReportService orderReportService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
CatalogSettings catalogSettings
)
{
@@ -28,7 +28,7 @@ public class ProductsAlsoPurchasedViewComponent : BaseViewComponent
_mediator = mediator;
_cacheBase = cacheBase;
_orderReportService = orderReportService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_catalogSettings = catalogSettings;
}
@@ -43,10 +43,10 @@ public class ProductsAlsoPurchasedViewComponent : BaseViewComponent
//load and cache report
var productIds = await _cacheBase.GetAsync(
- string.Format(CacheKeyConst.PRODUCTS_ALSO_PURCHASED_IDS_KEY, productId, _workContext.CurrentStore.Id),
+ string.Format(CacheKeyConst.PRODUCTS_ALSO_PURCHASED_IDS_KEY, productId, _workContextAccessor.WorkContext.CurrentStore.Id),
() =>
_orderReportService
- .GetAlsoPurchasedProductsIds(_workContext.CurrentStore.Id, productId,
+ .GetAlsoPurchasedProductsIds(_workContextAccessor.WorkContext.CurrentStore.Id, productId,
_catalogSettings.ProductsAlsoPurchasedNumber)
);
@@ -75,7 +75,7 @@ public class ProductsAlsoPurchasedViewComponent : BaseViewComponent
private readonly IMediator _mediator;
private readonly ICacheBase _cacheBase;
private readonly IOrderReportService _orderReportService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly CatalogSettings _catalogSettings;
#endregion
diff --git a/src/Web/Grand.Web/Components/PushNotificationsRegistration.cs b/src/Web/Grand.Web/Components/PushNotificationsRegistration.cs
index 12e3bcd52..7e79785ef 100644
--- a/src/Web/Grand.Web/Components/PushNotificationsRegistration.cs
+++ b/src/Web/Grand.Web/Components/PushNotificationsRegistration.cs
@@ -9,11 +9,11 @@ namespace Grand.Web.Components;
public class PushNotificationsRegistration : BaseViewComponent
{
private readonly PushNotificationsSettings _pushNotificationsSettings;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public PushNotificationsRegistration(IWorkContext workContext, PushNotificationsSettings pushNotificationsSettings)
+ public PushNotificationsRegistration(IWorkContextAccessor workContextAccessor, PushNotificationsSettings pushNotificationsSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_pushNotificationsSettings = pushNotificationsSettings;
}
@@ -34,7 +34,7 @@ public class PushNotificationsRegistration : BaseViewComponent
if (!_pushNotificationsSettings.Enabled) return Content("");
if (!_pushNotificationsSettings.AllowGuestNotifications &&
- string.IsNullOrEmpty(_workContext.CurrentCustomer.Email))
+ string.IsNullOrEmpty(_workContextAccessor.WorkContext.CurrentCustomer.Email))
return Content("");
return View(model);
diff --git a/src/Web/Grand.Web/Components/RecentlyViewedProductsBlock.cs b/src/Web/Grand.Web/Components/RecentlyViewedProductsBlock.cs
index 8217a1004..95b69b5a6 100644
--- a/src/Web/Grand.Web/Components/RecentlyViewedProductsBlock.cs
+++ b/src/Web/Grand.Web/Components/RecentlyViewedProductsBlock.cs
@@ -13,12 +13,12 @@ public class RecentlyViewedProductsBlockViewComponent : BaseViewComponent
#region Constructors
public RecentlyViewedProductsBlockViewComponent(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IRecentlyViewedProductsService recentlyViewedProductsService,
IMediator mediator,
CatalogSettings catalogSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_recentlyViewedProductsService = recentlyViewedProductsService;
_mediator = mediator;
_catalogSettings = catalogSettings;
@@ -34,7 +34,7 @@ public class RecentlyViewedProductsBlockViewComponent : BaseViewComponent
return Content("");
var preparePictureModel = productThumbPictureSize.HasValue;
- var products = await _recentlyViewedProductsService.GetRecentlyViewedProducts(_workContext.CurrentCustomer.Id,
+ var products = await _recentlyViewedProductsService.GetRecentlyViewedProducts(_workContextAccessor.WorkContext.CurrentCustomer.Id,
_catalogSettings.RecentlyViewedProductsNumber);
if (!products.Any())
@@ -55,7 +55,7 @@ public class RecentlyViewedProductsBlockViewComponent : BaseViewComponent
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IRecentlyViewedProductsService _recentlyViewedProductsService;
private readonly IMediator _mediator;
diff --git a/src/Web/Grand.Web/Components/SearchBox.cs b/src/Web/Grand.Web/Components/SearchBox.cs
index 67079a46d..064ae18bf 100644
--- a/src/Web/Grand.Web/Components/SearchBox.cs
+++ b/src/Web/Grand.Web/Components/SearchBox.cs
@@ -9,22 +9,22 @@ namespace Grand.Web.Components;
public class SearchBoxViewComponent : BaseViewComponent
{
private readonly IMediator _mediator;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public SearchBoxViewComponent(
IMediator mediator,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_mediator = mediator;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var model = await _mediator.Send(new GetSearchBox {
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore,
- Language = _workContext.WorkingLanguage
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage
});
return View(model);
}
diff --git a/src/Web/Grand.Web/Components/SuggestedProducts.cs b/src/Web/Grand.Web/Components/SuggestedProducts.cs
index 21cadcbd0..b4ea6b0b4 100644
--- a/src/Web/Grand.Web/Components/SuggestedProducts.cs
+++ b/src/Web/Grand.Web/Components/SuggestedProducts.cs
@@ -13,11 +13,11 @@ public class SuggestedProductsViewComponent : BaseViewComponent
#region Constructors
public SuggestedProductsViewComponent(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator,
CatalogSettings catalogSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_catalogSettings = catalogSettings;
}
@@ -32,7 +32,7 @@ public class SuggestedProductsViewComponent : BaseViewComponent
return Content("");
var products = await _mediator.Send(new GetSuggestedProductsQuery {
- CustomerTagIds = _workContext.CurrentCustomer.CustomerTags.ToArray(),
+ CustomerTagIds = _workContextAccessor.WorkContext.CurrentCustomer.CustomerTags.ToArray(),
ProductsNumber = _catalogSettings.SuggestedProductsNumber
});
@@ -54,7 +54,7 @@ public class SuggestedProductsViewComponent : BaseViewComponent
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
private readonly CatalogSettings _catalogSettings;
diff --git a/src/Web/Grand.Web/Components/VendorContact.cs b/src/Web/Grand.Web/Components/VendorContact.cs
index a5e0c17b4..9f8366fd2 100644
--- a/src/Web/Grand.Web/Components/VendorContact.cs
+++ b/src/Web/Grand.Web/Components/VendorContact.cs
@@ -17,13 +17,13 @@ public class VendorContactViewComponent : BaseViewComponent
public VendorContactViewComponent(
IVendorService vendorService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
VendorSettings vendorSettings,
CommonSettings commonSettings,
CaptchaSettings captchaSettings)
{
_vendorService = vendorService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_vendorSettings = vendorSettings;
_commonSettings = commonSettings;
_captchaSettings = captchaSettings;
@@ -43,12 +43,12 @@ public class VendorContactViewComponent : BaseViewComponent
return Content("");
var model = new ContactVendorModel {
- Email = _workContext.CurrentCustomer.Email,
- FullName = _workContext.CurrentCustomer.GetFullName(),
+ Email = _workContextAccessor.WorkContext.CurrentCustomer.Email,
+ FullName = _workContextAccessor.WorkContext.CurrentCustomer.GetFullName(),
SubjectEnabled = _commonSettings.SubjectFieldOnContactUsForm,
DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnContactUsPage,
VendorId = vendor.Id,
- VendorName = vendor.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id)
+ VendorName = vendor.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id)
};
return View(model);
@@ -59,7 +59,7 @@ public class VendorContactViewComponent : BaseViewComponent
#region Fields
private readonly IVendorService _vendorService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly VendorSettings _vendorSettings;
private readonly CommonSettings _commonSettings;
private readonly CaptchaSettings _captchaSettings;
diff --git a/src/Web/Grand.Web/Components/VendorNavigation.cs b/src/Web/Grand.Web/Components/VendorNavigation.cs
index ab4bcb775..36023d890 100644
--- a/src/Web/Grand.Web/Components/VendorNavigation.cs
+++ b/src/Web/Grand.Web/Components/VendorNavigation.cs
@@ -11,14 +11,14 @@ public class VendorNavigationViewComponent : BaseViewComponent
{
private readonly IMediator _mediator;
private readonly VendorSettings _vendorSettings;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public VendorNavigationViewComponent(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator,
VendorSettings vendorSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_vendorSettings = vendorSettings;
}
@@ -29,7 +29,7 @@ public class VendorNavigationViewComponent : BaseViewComponent
return Content("");
var model = await _mediator.Send(new GetVendorNavigation {
- Language = _workContext.WorkingLanguage
+ Language = _workContextAccessor.WorkContext.WorkingLanguage
});
return !model.Vendors.Any() ? Content("") : View(model);
diff --git a/src/Web/Grand.Web/Components/VendorReviews.cs b/src/Web/Grand.Web/Components/VendorReviews.cs
index fc7383af0..393eea79a 100644
--- a/src/Web/Grand.Web/Components/VendorReviews.cs
+++ b/src/Web/Grand.Web/Components/VendorReviews.cs
@@ -16,13 +16,13 @@ public class VendorReviewsViewComponent : BaseViewComponent
public VendorReviewsViewComponent(
IVendorService vendorService,
IGroupService groupService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator,
VendorSettings vendorSettings)
{
_vendorService = vendorService;
_groupService = groupService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_vendorSettings = vendorSettings;
}
@@ -40,7 +40,7 @@ public class VendorReviewsViewComponent : BaseViewComponent
var model = await _mediator.Send(new GetVendorReviews { Vendor = vendor });
//only registered users can leave reviews
- if (await _groupService.IsGuest(_workContext.CurrentCustomer) &&
+ if (await _groupService.IsGuest(_workContextAccessor.WorkContext.CurrentCustomer) &&
!_vendorSettings.AllowAnonymousUsersToReviewVendor)
model.AddVendorReview.NotAllowAnonymousUsersToReviewVendor = true;
@@ -55,7 +55,7 @@ public class VendorReviewsViewComponent : BaseViewComponent
private readonly IVendorService _vendorService;
private readonly IGroupService _groupService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
private readonly VendorSettings _vendorSettings;
diff --git a/src/Web/Grand.Web/Components/Widget.cs b/src/Web/Grand.Web/Components/Widget.cs
index 2badddf37..9447a5a47 100644
--- a/src/Web/Grand.Web/Components/Widget.cs
+++ b/src/Web/Grand.Web/Components/Widget.cs
@@ -13,27 +13,27 @@ public class WidgetViewComponent : BaseViewComponent
{
private readonly ICacheBase _cacheBase;
private readonly IWidgetService _widgetService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public WidgetViewComponent(IWorkContext workContext, ICacheBase cacheBase, IWidgetService widgetService)
+ public WidgetViewComponent(IWorkContextAccessor workContextAccessor, ICacheBase cacheBase, IWidgetService widgetService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_cacheBase = cacheBase;
_widgetService = widgetService;
}
public async Task<IViewComponentResult> InvokeAsync(string widgetZone, object additionalData = null)
{
- var cacheKey = string.Format(CacheKeyConst.WIDGET_MODEL_KEY, _workContext.CurrentStore.Id,
- string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),
+ var cacheKey = string.Format(CacheKeyConst.WIDGET_MODEL_KEY, _workContextAccessor.WorkContext.CurrentStore.Id,
+ string.Join(",", _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()),
widgetZone);
var cachedModel = await _cacheBase.GetAsync(cacheKey, async () =>
{
//model
var model = new List<WidgetModel>();
- var widgets = await _widgetService.LoadActiveWidgetsByWidgetZone(widgetZone, _workContext.CurrentStore.Id,
- _workContext.CurrentCustomer);
+ var widgets = await _widgetService.LoadActiveWidgetsByWidgetZone(widgetZone, _workContextAccessor.WorkContext.CurrentStore.Id,
+ _workContextAccessor.WorkContext.CurrentCustomer);
foreach (var widget in widgets)
{
var viewComponentName = await widget.GetPublicViewComponentName(widgetZone);
diff --git a/src/Web/Grand.Web/Controllers/AccountController.cs b/src/Web/Grand.Web/Controllers/AccountController.cs
index 0866bb187..506ff202a 100644
--- a/src/Web/Grand.Web/Controllers/AccountController.cs
+++ b/src/Web/Grand.Web/Controllers/AccountController.cs
@@ -35,7 +35,7 @@ public class AccountController : BasePublicController
public AccountController(
IGrandAuthenticationService authenticationService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ICustomerService customerService,
IGroupService groupService,
ICustomerManagerService customerManagerService,
@@ -47,7 +47,7 @@ public class AccountController : BasePublicController
{
_authenticationService = authenticationService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_customerService = customerService;
_groupService = groupService;
_customerManagerService = customerManagerService;
@@ -70,7 +70,7 @@ public class AccountController : BasePublicController
return RedirectToRoute("CustomerInfo");
var model = await _mediator.Send(new GetAuctions
- { Customer = _workContext.CurrentCustomer, Language = _workContext.WorkingLanguage });
+ { Customer = _workContextAccessor.WorkContext.CurrentCustomer, Language = _workContextAccessor.WorkContext.WorkingLanguage });
return View(model);
}
@@ -86,7 +86,7 @@ public class AccountController : BasePublicController
if (_customerSettings.HideNotesTab)
return RedirectToRoute("CustomerInfo");
- var model = await _mediator.Send(new GetNotes { Customer = _workContext.CurrentCustomer });
+ var model = await _mediator.Send(new GetNotes { Customer = _workContextAccessor.WorkContext.CurrentCustomer });
return View(model);
}
@@ -103,8 +103,8 @@ public class AccountController : BasePublicController
return RedirectToRoute("CustomerInfo");
var model = await _mediator.Send(new GetDocuments {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
Command = command
});
@@ -123,7 +123,7 @@ public class AccountController : BasePublicController
return RedirectToRoute("CustomerInfo");
var model = await _mediator.Send(new GetReviews
- { Customer = _workContext.CurrentCustomer, Language = _workContext.WorkingLanguage });
+ { Customer = _workContextAccessor.WorkContext.CurrentCustomer, Language = _workContextAccessor.WorkContext.WorkingLanguage });
return View(model);
}
@@ -140,7 +140,7 @@ public class AccountController : BasePublicController
return RedirectToRoute("CustomerInfo");
var model = await _mediator.Send(new GetCourses
- { Customer = _workContext.CurrentCustomer, Store = _workContext.CurrentStore });
+ { Customer = _workContextAccessor.WorkContext.CurrentCustomer, Store = _workContextAccessor.WorkContext.CurrentStore });
return View(model);
}
@@ -151,7 +151,7 @@ public class AccountController : BasePublicController
private readonly IGrandAuthenticationService _authenticationService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ICustomerService _customerService;
private readonly IGroupService _groupService;
private readonly ICustomerManagerService _customerManagerService;
@@ -240,8 +240,8 @@ public class AccountController : BasePublicController
if (_customerSettings.TwoFactorAuthenticationType != TwoFactorAuthenticationType.AppVerification)
await _mediator.Send(new GetTwoFactorAuthentication {
Customer = customer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return View();
@@ -316,19 +316,19 @@ public class AccountController : BasePublicController
public virtual async Task<IActionResult> Logout(
[FromServices] StoreInformationSettings storeInformationSettings)
{
- if (_workContext.OriginalCustomerIfImpersonated != null)
+ if (_workContextAccessor.WorkContext.OriginalCustomerIfImpersonated != null)
{
//logout impersonated customer
- await _customerService.UpdateUserField<int?>(_workContext.OriginalCustomerIfImpersonated,
+ await _customerService.UpdateUserField<int?>(_workContextAccessor.WorkContext.OriginalCustomerIfImpersonated,
SystemCustomerFieldNames.ImpersonatedCustomerId, null);
//redirect back to customer details page (admin area)
return RedirectToAction("Edit", "Customer",
- new { id = _workContext.CurrentCustomer.Id, area = "Admin" });
+ new { id = _workContextAccessor.WorkContext.CurrentCustomer.Id, area = "Admin" });
}
//raise event
- await _mediator.Publish(new CustomerLoggedOutEvent(_workContext.CurrentCustomer));
+ await _mediator.Publish(new CustomerLoggedOutEvent(_workContextAccessor.WorkContext.CurrentCustomer));
//standard logout
await _authenticationService.SignOut();
@@ -364,8 +364,8 @@ public class AccountController : BasePublicController
var customer = await _customerService.GetCustomerByEmail(model.Email);
await _mediator.Send(new PasswordRecoverySendCommand {
Customer = customer,
- Store = _workContext.CurrentStore,
- Language = _workContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
Model = model
});
@@ -422,13 +422,13 @@ public class AccountController : BasePublicController
return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled });
//check if customer is registered.
- if (await _groupService.IsRegistered(_workContext.CurrentCustomer)) return RedirectToRoute("HomePage");
+ if (await _groupService.IsRegistered(_workContextAccessor.WorkContext.CurrentCustomer)) return RedirectToRoute("HomePage");
var model = await _mediator.Send(new GetRegister {
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
ExcludeProperties = false,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return View(model);
@@ -445,45 +445,45 @@ public class AccountController : BasePublicController
return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled });
//check if customer is registered.
- if (await _groupService.IsRegistered(_workContext.CurrentCustomer)) return RedirectToRoute("HomePage");
+ if (await _groupService.IsRegistered(_workContextAccessor.WorkContext.CurrentCustomer)) return RedirectToRoute("HomePage");
if (ModelState.IsValid)
{
if (_customerSettings.UsernamesEnabled && model.Username != null) model.Username = model.Username.Trim();
var isApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
- var registrationRequest = new RegistrationRequest(_workContext.CurrentCustomer, model.Email,
+ var registrationRequest = new RegistrationRequest(_workContextAccessor.WorkContext.CurrentCustomer, model.Email,
_customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password,
- _customerSettings.DefaultPasswordFormat, _workContext.CurrentStore.Id, isApproved);
+ _customerSettings.DefaultPasswordFormat, _workContextAccessor.WorkContext.CurrentStore.Id, isApproved);
await _customerManagerService.RegisterCustomer(registrationRequest);
var customerAttributes = await _mediator.Send(new GetParseCustomAttributes
{ SelectedAttributes = model.SelectedAttributes });
await _mediator.Send(new CustomerRegisteredCommand {
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
CustomerAttributes = customerAttributes,
Model = model,
- Store = _workContext.CurrentStore
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
//login customer now
if (isApproved)
- await _authenticationService.SignIn(_workContext.CurrentCustomer, true);
+ await _authenticationService.SignIn(_workContextAccessor.WorkContext.CurrentCustomer, true);
//raise event
- await _mediator.Publish(new CustomerRegisteredEvent(_workContext.CurrentCustomer));
+ await _mediator.Publish(new CustomerRegisteredEvent(_workContextAccessor.WorkContext.CurrentCustomer));
switch (_customerSettings.UserRegistrationType)
{
case UserRegistrationType.EmailValidation:
{
//email validation message
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.AccountActivationToken, Guid.NewGuid().ToString());
await _messageProviderService.SendCustomerEmailValidationMessage(
- _workContext.CurrentCustomer, _workContext.CurrentStore,
- _workContext.WorkingLanguage.Id);
+ _workContextAccessor.WorkContext.CurrentCustomer, _workContextAccessor.WorkContext.CurrentStore,
+ _workContextAccessor.WorkContext.WorkingLanguage.Id);
//result
return RedirectToRoute("RegisterResult",
@@ -497,8 +497,8 @@ public class AccountController : BasePublicController
case UserRegistrationType.Standard:
{
//send customer welcome message
- await _messageProviderService.SendCustomerWelcomeMessage(_workContext.CurrentCustomer,
- _workContext.CurrentStore, _workContext.WorkingLanguage.Id);
+ await _messageProviderService.SendCustomerWelcomeMessage(_workContextAccessor.WorkContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.CurrentStore, _workContextAccessor.WorkContext.WorkingLanguage.Id);
var redirectUrl = Url.RouteUrl("RegisterResult",
new { resultId = (int)UserRegistrationType.Standard }, HttpContext.Request.Scheme);
@@ -516,10 +516,10 @@ public class AccountController : BasePublicController
//If we got this far, something failed, redisplay form
model = await _mediator.Send(new GetRegister {
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
ExcludeProperties = true,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Model = model,
OverrideCustomCustomerAttributes = await _mediator.Send(new GetParseCustomAttributes
{ SelectedAttributes = model.SelectedAttributes })
@@ -569,8 +569,8 @@ public class AccountController : BasePublicController
if (!_customerSettings.UsernamesEnabled || string.IsNullOrWhiteSpace(username))
return Json(new { Available = false, Text = statusText });
- if (_workContext.CurrentCustomer is { Username: not null } &&
- _workContext.CurrentCustomer.Username.Equals(username, StringComparison.OrdinalIgnoreCase))
+ if (_workContextAccessor.WorkContext.CurrentCustomer is { Username: not null } &&
+ _workContextAccessor.WorkContext.CurrentCustomer.Username.Equals(username, StringComparison.OrdinalIgnoreCase))
{
statusText = _translationService.GetResource("Account.CheckUsernameAvailability.CurrentUsername");
}
@@ -603,13 +603,13 @@ public class AccountController : BasePublicController
//activate user account
customer.Active = true;
- customer.StoreId = _workContext.CurrentStore.Id;
+ customer.StoreId = _workContextAccessor.WorkContext.CurrentStore.Id;
await _customerService.UpdateActive(customer);
await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.AccountActivationToken, "");
//send welcome message
- await _messageProviderService.SendCustomerWelcomeMessage(customer, _workContext.CurrentStore,
- _workContext.WorkingLanguage.Id);
+ await _messageProviderService.SendCustomerWelcomeMessage(customer, _workContextAccessor.WorkContext.CurrentStore,
+ _workContextAccessor.WorkContext.WorkingLanguage.Id);
var model = new AccountActivationModel {
Result = _translationService.GetResource("Account.AccountActivation.Activated")
@@ -626,10 +626,10 @@ public class AccountController : BasePublicController
public virtual async Task<IActionResult> Info()
{
var model = await _mediator.Send(new GetInfo {
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
ExcludeProperties = false,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return View(model);
}
@@ -642,14 +642,14 @@ public class AccountController : BasePublicController
if (ModelState.IsValid)
{
await _mediator.Send(new UpdateCustomerInfoCommand {
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
CustomerAttributes = await _mediator.Send(new GetParseCustomAttributes {
SelectedAttributes = model.SelectedAttributes,
- CustomerCustomAttribute = _workContext.CurrentCustomer.Attributes.ToList()
+ CustomerCustomAttribute = _workContextAccessor.WorkContext.CurrentCustomer.Attributes.ToList()
}),
Model = model,
- OriginalCustomerIfImpersonated = _workContext.OriginalCustomerIfImpersonated,
- Store = _workContext.CurrentStore
+ OriginalCustomerIfImpersonated = _workContextAccessor.WorkContext.OriginalCustomerIfImpersonated,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return RedirectToRoute("CustomerInfo");
}
@@ -657,13 +657,13 @@ public class AccountController : BasePublicController
//If we got this far, something failed, redisplay form
model = await _mediator.Send(new GetInfo {
Model = model,
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
ExcludeProperties = true,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
OverrideCustomCustomerAttributes = await _mediator.Send(new GetParseCustomAttributes {
SelectedAttributes = model.SelectedAttributes,
- CustomerCustomAttribute = _workContext.CurrentCustomer.Attributes.ToList()
+ CustomerCustomAttribute = _workContextAccessor.WorkContext.CurrentCustomer.Attributes.ToList()
})
});
@@ -677,7 +677,7 @@ public class AccountController : BasePublicController
[FromServices] IExternalAuthenticationService openAuthenticationService)
{
//ensure it's our record
- var ear = (await openAuthenticationService.GetExternalIdentifiers(_workContext.CurrentCustomer))
+ var ear = (await openAuthenticationService.GetExternalIdentifiers(_workContextAccessor.WorkContext.CurrentCustomer))
.FirstOrDefault(x => x.Id == id);
if (ear == null)
@@ -699,7 +699,7 @@ public class AccountController : BasePublicController
if (!_customerSettings.AllowUsersToExportData)
return Challenge();
- var model = await _mediator.Send(new GetCustomerData(_workContext.CurrentCustomer));
+ var model = await _mediator.Send(new GetCustomerData(_workContextAccessor.WorkContext.CurrentCustomer));
return File(model, "text/xls", "PersonalInfo.xlsx");
}
@@ -713,9 +713,9 @@ public class AccountController : BasePublicController
public virtual async Task<IActionResult> Addresses()
{
var model = await _mediator.Send(new GetAddressList {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return View(model);
}
@@ -725,7 +725,7 @@ public class AccountController : BasePublicController
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> AddressDelete(string addressId)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
//find address (ensure that it belongs to the current customer)
var address = customer.Addresses.FirstOrDefault(a => a.Id == addressId);
@@ -746,16 +746,16 @@ public class AccountController : BasePublicController
public virtual async Task<IActionResult> AddressAdd()
{
var countries =
- await _countryService.GetAllCountries(_workContext.WorkingLanguage.Id, _workContext.CurrentStore.Id);
+ await _countryService.GetAllCountries(_workContextAccessor.WorkContext.WorkingLanguage.Id, _workContextAccessor.WorkContext.CurrentStore.Id);
var model = new CustomerAddressEditModel {
Address = await _mediator.Send(new GetAddressModel {
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Model = null,
Address = null,
ExcludeProperties = false,
PrePopulateWithCustomerFields = true,
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
LoadCountries = () => countries
})
};
@@ -769,11 +769,11 @@ public class AccountController : BasePublicController
public virtual async Task<IActionResult> AddressAdd(CustomerAddressEditModel model,
[FromServices] AddressSettings addressSettings)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
if (ModelState.IsValid)
{
- var address = model.Address.ToEntity(_workContext.CurrentCustomer, addressSettings);
+ var address = model.Address.ToEntity(_workContextAccessor.WorkContext.CurrentCustomer, addressSettings);
address.Attributes = await _mediator.Send(new GetParseCustomAddressAttributes
{ SelectedAttributes = model.Address.SelectedAttributes });
customer.Addresses.Add(address);
@@ -784,15 +784,15 @@ public class AccountController : BasePublicController
}
var countries =
- await _countryService.GetAllCountries(_workContext.WorkingLanguage.Id, _workContext.CurrentStore.Id);
+ await _countryService.GetAllCountries(_workContextAccessor.WorkContext.WorkingLanguage.Id, _workContextAccessor.WorkContext.CurrentStore.Id);
//If we got this far, something failed, redisplay form
model.Address = await _mediator.Send(new GetAddressModel {
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Model = model.Address,
Address = null,
ExcludeProperties = true,
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
LoadCountries = () => countries,
OverrideAttributes = await _mediator.Send(new GetParseCustomAddressAttributes
{ SelectedAttributes = model.Address.SelectedAttributes })
@@ -805,7 +805,7 @@ public class AccountController : BasePublicController
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> AddressEdit(string addressId)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
//find address (ensure that it belongs to the current customer)
var address = customer.Addresses.FirstOrDefault(a => a.Id == addressId);
if (address == null)
@@ -813,15 +813,15 @@ public class AccountController : BasePublicController
return RedirectToRoute("CustomerAddresses");
var countries =
- await _countryService.GetAllCountries(_workContext.WorkingLanguage.Id, _workContext.CurrentStore.Id);
+ await _countryService.GetAllCountries(_workContextAccessor.WorkContext.WorkingLanguage.Id, _workContextAccessor.WorkContext.CurrentStore.Id);
var model = new CustomerAddressEditModel();
model.Address = await _mediator.Send(new GetAddressModel {
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Model = model.Address,
Address = address,
ExcludeProperties = false,
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
LoadCountries = () => countries
});
@@ -834,7 +834,7 @@ public class AccountController : BasePublicController
public virtual async Task<IActionResult> AddressEdit(CustomerAddressEditModel model,
[FromServices] AddressSettings addressSettings)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
//find address (ensure that it belongs to the current customer)
var address = customer.Addresses.FirstOrDefault(a => a.Id == model.Address.Id);
if (address == null)
@@ -843,7 +843,7 @@ public class AccountController : BasePublicController
if (ModelState.IsValid)
{
- address = model.Address.ToEntity(address, _workContext.CurrentCustomer, addressSettings);
+ address = model.Address.ToEntity(address, _workContextAccessor.WorkContext.CurrentCustomer, addressSettings);
address.Attributes = await _mediator.Send(new GetParseCustomAddressAttributes
{ SelectedAttributes = model.Address.SelectedAttributes });
await _customerService.UpdateAddress(address, customer.Id);
@@ -857,15 +857,15 @@ public class AccountController : BasePublicController
}
var countries =
- await _countryService.GetAllCountries(_workContext.WorkingLanguage.Id, _workContext.CurrentStore.Id);
+ await _countryService.GetAllCountries(_workContextAccessor.WorkContext.WorkingLanguage.Id, _workContextAccessor.WorkContext.CurrentStore.Id);
//If we got this far, something failed, redisplay form
model.Address = await _mediator.Send(new GetAddressModel {
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Model = model.Address,
Address = address,
ExcludeProperties = true,
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
LoadCountries = () => countries,
OverrideAttributes = await _mediator.Send(new GetParseCustomAddressAttributes
{ SelectedAttributes = model.Address.SelectedAttributes })
@@ -886,9 +886,9 @@ public class AccountController : BasePublicController
return RedirectToRoute("CustomerInfo");
var model = await _mediator.Send(new GetDownloadableProducts {
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore,
- Language = _workContext.WorkingLanguage
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage
});
return View(model);
}
@@ -910,7 +910,7 @@ public class AccountController : BasePublicController
{
var model = new ChangePasswordModel {
PasswordIsExpired = await _mediator.Send(new GetPasswordIsExpiredQuery
- { Customer = _workContext.CurrentCustomer })
+ { Customer = _workContextAccessor.WorkContext.CurrentCustomer })
};
return View(model);
@@ -923,13 +923,13 @@ public class AccountController : BasePublicController
{
if (!ModelState.IsValid) return View(model);
- var changePasswordRequest = new ChangePasswordRequest(_workContext.CurrentCustomer.Email,
+ var changePasswordRequest = new ChangePasswordRequest(_workContextAccessor.WorkContext.CurrentCustomer.Email,
_customerSettings.DefaultPasswordFormat, model.NewPassword, model.OldPassword);
await _customerManagerService.ChangePassword(changePasswordRequest);
//sign in
- await _authenticationService.SignIn(_workContext.CurrentCustomer, true);
+ await _authenticationService.SignIn(_workContextAccessor.WorkContext.CurrentCustomer, true);
model.Result = _translationService.GetResource("Account.ChangePassword.Success");
return View(model);
@@ -963,8 +963,8 @@ public class AccountController : BasePublicController
//delete account
await _mediator.Send(new DeleteAccountCommand {
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
IpAddress = HttpContext.Connection?.RemoteIpAddress?.ToString()
});
@@ -989,13 +989,13 @@ public class AccountController : BasePublicController
if (!_customerSettings.TwoFactorAuthenticationEnabled)
return RedirectToRoute("CustomerInfo");
- if (_workContext.CurrentCustomer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.TwoFactorEnabled))
+ if (_workContextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.TwoFactorEnabled))
return RedirectToRoute("CustomerInfo");
var model = await _mediator.Send(new GetTwoFactorAuthentication {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return View(model);
}
@@ -1010,7 +1010,7 @@ public class AccountController : BasePublicController
if (!_customerSettings.TwoFactorAuthenticationEnabled)
return RedirectToRoute("CustomerInfo");
- if (_workContext.CurrentCustomer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.TwoFactorEnabled))
+ if (_workContextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.TwoFactorEnabled))
return RedirectToRoute("CustomerInfo");
if (string.IsNullOrEmpty(model.Code))
@@ -1021,11 +1021,11 @@ public class AccountController : BasePublicController
else
{
if (await twoFactorAuthenticationService.AuthenticateTwoFactor(model.SecretKey, model.Code,
- _workContext.CurrentCustomer, _customerSettings.TwoFactorAuthenticationType))
+ _workContextAccessor.WorkContext.CurrentCustomer, _customerSettings.TwoFactorAuthenticationType))
{
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.TwoFactorEnabled, true);
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.TwoFactorSecretKey, model.SecretKey);
Success(_translationService.GetResource("Account.TwoFactorAuth.Enabled"));
@@ -1048,13 +1048,13 @@ public class AccountController : BasePublicController
if (!_customerSettings.TwoFactorAuthenticationEnabled)
return RedirectToRoute("CustomerInfo");
- if (!_workContext.CurrentCustomer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.TwoFactorEnabled))
+ if (!_workContextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.TwoFactorEnabled))
return RedirectToRoute("CustomerInfo");
_ = await _mediator.Send(new GetTwoFactorAuthentication {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
var model = new CustomerInfoModel.TwoFactorAuthorizationModel {
@@ -1073,7 +1073,7 @@ public class AccountController : BasePublicController
if (!_customerSettings.TwoFactorAuthenticationEnabled)
return RedirectToRoute("CustomerInfo");
- if (!_workContext.CurrentCustomer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.TwoFactorEnabled))
+ if (!_workContextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.TwoFactorEnabled))
return RedirectToRoute("CustomerInfo");
if (string.IsNullOrEmpty(model.Code))
@@ -1084,14 +1084,14 @@ public class AccountController : BasePublicController
else
{
var secretKey =
- _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames
+ _workContextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames
.TwoFactorSecretKey);
if (await twoFactorAuthenticationService.AuthenticateTwoFactor(secretKey, model.Code,
- _workContext.CurrentCustomer, _customerSettings.TwoFactorAuthenticationType))
+ _workContextAccessor.WorkContext.CurrentCustomer, _customerSettings.TwoFactorAuthenticationType))
{
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.TwoFactorEnabled, false);
- await _customerService.UpdateUserField<string>(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField<string>(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.TwoFactorSecretKey, null);
Success(_translationService.GetResource("Account.TwoFactorAuth.Disabled"));
@@ -1114,13 +1114,13 @@ public class AccountController : BasePublicController
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> SubAccounts()
{
- if (!await _groupService.IsOwner(_workContext.CurrentCustomer))
+ if (!await _groupService.IsOwner(_workContextAccessor.WorkContext.CurrentCustomer))
return Challenge();
if (_customerSettings.HideSubAccountsTab)
return RedirectToRoute("CustomerInfo");
- var model = await _mediator.Send(new GetSubAccounts { Customer = _workContext.CurrentCustomer });
+ var model = await _mediator.Send(new GetSubAccounts { Customer = _workContextAccessor.WorkContext.CurrentCustomer });
return View(model);
}
@@ -1129,7 +1129,7 @@ public class AccountController : BasePublicController
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> SubAccountAdd()
{
- if (!await _groupService.IsOwner(_workContext.CurrentCustomer))
+ if (!await _groupService.IsOwner(_workContextAccessor.WorkContext.CurrentCustomer))
return Challenge();
var model = new SubAccountCreateModel {
@@ -1143,15 +1143,15 @@ public class AccountController : BasePublicController
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> SubAccountAdd(SubAccountCreateModel model)
{
- if (!await _groupService.IsOwner(_workContext.CurrentCustomer))
+ if (!await _groupService.IsOwner(_workContextAccessor.WorkContext.CurrentCustomer))
return Challenge();
if (!ModelState.IsValid) return View(model);
await _mediator.Send(new SubAccountAddCommand {
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
Model = model,
- Store = _workContext.CurrentStore
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return RedirectToRoute("CustomerSubAccounts");
@@ -1161,11 +1161,11 @@ public class AccountController : BasePublicController
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> SubAccountEdit(string id)
{
- if (!await _groupService.IsOwner(_workContext.CurrentCustomer))
+ if (!await _groupService.IsOwner(_workContextAccessor.WorkContext.CurrentCustomer))
return Challenge();
var model = await _mediator.Send(new GetSubAccount
- { CustomerId = id, CurrentCustomer = _workContext.CurrentCustomer });
+ { CustomerId = id, CurrentCustomer = _workContextAccessor.WorkContext.CurrentCustomer });
return View(model);
}
@@ -1175,15 +1175,15 @@ public class AccountController : BasePublicController
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> SubAccountEdit(SubAccountEditModel model)
{
- if (!await _groupService.IsOwner(_workContext.CurrentCustomer))
+ if (!await _groupService.IsOwner(_workContextAccessor.WorkContext.CurrentCustomer))
return Challenge();
if (!ModelState.IsValid) return View(model);
_ = await _mediator.Send(new SubAccountEditCommand {
- CurrentCustomer = _workContext.CurrentCustomer,
+ CurrentCustomer = _workContextAccessor.WorkContext.CurrentCustomer,
EditModel = model,
- Store = _workContext.CurrentStore
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return RedirectToRoute("CustomerSubAccounts");
@@ -1194,11 +1194,11 @@ public class AccountController : BasePublicController
[CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)]
public virtual async Task<IActionResult> SubAccountDelete(string id)
{
- if (!await _groupService.IsOwner(_workContext.CurrentCustomer))
+ if (!await _groupService.IsOwner(_workContextAccessor.WorkContext.CurrentCustomer))
return Challenge();
var result = await _mediator.Send(new SubAccountDeleteCommand {
- CurrentCustomer = _workContext.CurrentCustomer,
+ CurrentCustomer = _workContextAccessor.WorkContext.CurrentCustomer,
CustomerId = id
});
diff --git a/src/Web/Grand.Web/Controllers/ActionCartController.cs b/src/Web/Grand.Web/Controllers/ActionCartController.cs
index 93f631693..b6d450b23 100644
--- a/src/Web/Grand.Web/Controllers/ActionCartController.cs
+++ b/src/Web/Grand.Web/Controllers/ActionCartController.cs
@@ -28,7 +28,7 @@ public class ActionCartController : BasePublicController
public ActionCartController(IProductService productService,
IShoppingCartService shoppingCartService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
ITranslationService translationService,
ICurrencyService currencyService,
@@ -38,7 +38,7 @@ public class ActionCartController : BasePublicController
{
_productService = productService;
_shoppingCartService = shoppingCartService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_translationService = translationService;
_currencyService = currencyService;
@@ -53,7 +53,7 @@ public class ActionCartController : BasePublicController
private readonly IProductService _productService;
private readonly IShoppingCartService _shoppingCartService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
private readonly ITranslationService _translationService;
private readonly ICurrencyService _currencyService;
@@ -70,7 +70,7 @@ public class ActionCartController : BasePublicController
//we can't add grouped products
if (product.ProductTypeId == ProductType.GroupedProduct)
return Json(new {
- redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) })
+ redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id) })
});
switch (cartType)
@@ -80,13 +80,13 @@ public class ActionCartController : BasePublicController
//we cannot add to the cart such products from category pages
return Json(new {
redirect = Url.RouteUrl("Product",
- new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) })
+ new { SeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id) })
});
case ShoppingCartType.ShoppingCart when product.EnteredPrice:
//cannot be added to the cart (requires a customer to enter price)
return Json(new {
redirect = Url.RouteUrl("Product",
- new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) })
+ new { SeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id) })
});
}
@@ -94,13 +94,13 @@ public class ActionCartController : BasePublicController
if (cartType == ShoppingCartType.ShoppingCart && allowedQuantities.Length > 0)
//cannot be added to the cart (requires a customer to select a quantity from drop down list)
return Json(new {
- redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) })
+ redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id) })
});
if (cartType != ShoppingCartType.Wishlist && product.ProductAttributeMappings.Any())
//product has some attributes
return Json(new {
- redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) })
+ redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id) })
});
return null;
@@ -108,9 +108,9 @@ public class ActionCartController : BasePublicController
private string GetWarehouse(Product product)
{
- return product.UseMultipleWarehouses ? _workContext.CurrentStore.DefaultWarehouseId :
- string.IsNullOrEmpty(_workContext.CurrentStore.DefaultWarehouseId) ? product.WarehouseId :
- _workContext.CurrentStore.DefaultWarehouseId;
+ return product.UseMultipleWarehouses ? _workContextAccessor.WorkContext.CurrentStore.DefaultWarehouseId :
+ string.IsNullOrEmpty(_workContextAccessor.WorkContext.CurrentStore.DefaultWarehouseId) ? product.WarehouseId :
+ _workContextAccessor.WorkContext.CurrentStore.DefaultWarehouseId;
}
private IActionResult ReturnFailMessage(Product product, ShoppingCartType shoppingCartTypeId)
@@ -153,7 +153,7 @@ public class ActionCartController : BasePublicController
if (double.TryParse(model.CustomerEnteredPrice, out var customerEnteredPrice))
customerEnteredPriceConverted =
await _currencyService.ConvertToPrimaryStoreCurrency(customerEnteredPrice,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
return customerEnteredPriceConverted;
}
@@ -177,11 +177,11 @@ public class ActionCartController : BasePublicController
if (redirect != null)
return redirect;
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var warehouseId = GetWarehouse(product);
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, model.ShoppingCartTypeId);
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id, model.ShoppingCartTypeId);
if (model.ShoppingCartTypeId != ShoppingCartType.Wishlist)
{
@@ -194,7 +194,7 @@ public class ActionCartController : BasePublicController
var addToCartWarnings = await _shoppingCartValidator
.GetShoppingCartItemWarnings(customer, new ShoppingCartItem {
ShoppingCartTypeId = model.ShoppingCartTypeId,
- StoreId = _workContext.CurrentStore.Id,
+ StoreId = _workContextAccessor.WorkContext.CurrentStore.Id,
WarehouseId = warehouseId,
Quantity = quantityToValidate
}, product, new ShoppingCartValidatorOptions {
@@ -205,7 +205,7 @@ public class ActionCartController : BasePublicController
//cannot be added to the cart
return Json(new {
redirect = Url.RouteUrl("Product",
- new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) })
+ new { SeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id) })
});
}
@@ -213,7 +213,7 @@ public class ActionCartController : BasePublicController
var addToCart = await _shoppingCartService.AddToCart(customer,
product.Id,
model.ShoppingCartTypeId,
- _workContext.CurrentStore.Id,
+ _workContextAccessor.WorkContext.CurrentStore.Id,
warehouseId,
quantity: model.Quantity,
validator: new ShoppingCartValidatorOptions {
@@ -227,7 +227,7 @@ public class ActionCartController : BasePublicController
if (addToCart.warnings.Any())
//cannot be added to the cart
return Json(new {
- redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) })
+ redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id) })
});
var addtoCartModel = await _mediator.Send(new GetAddToCart {
@@ -236,10 +236,10 @@ public class ActionCartController : BasePublicController
ShoppingCartItem = addToCart.shoppingCartItem,
Quantity = model.Quantity,
CartType = model.ShoppingCartTypeId,
- Currency = _workContext.WorkingCurrency,
- Store = _workContext.CurrentStore,
- Language = _workContext.WorkingLanguage,
- TaxDisplayType = _workContext.TaxDisplayType
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType
});
//added to the cart/wishlist
@@ -254,7 +254,7 @@ public class ActionCartController : BasePublicController
});
//display notification message and update appropriate blocks
- var qty = (await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var qty = (await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.Wishlist)).Sum(x => x.Quantity);
var updatetopwishlistsectionhtml =
string.Format(_translationService.GetResource("Wishlist.HeaderQuantity"), qty);
@@ -288,17 +288,17 @@ public class ActionCartController : BasePublicController
var updatetopcartsectionhtml = string.Format(
_translationService.GetResource("ShoppingCart.HeaderQuantity"),
- (await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ (await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
shoppingCartTypes.ToArray()))
.Sum(x => x.Quantity));
var miniShoppingCartmodel = _shoppingCartSettings.MiniShoppingCartEnabled
? await _mediator.Send(new GetMiniShoppingCart {
- Customer = _workContext.CurrentCustomer,
- Currency = _workContext.WorkingCurrency,
- Language = _workContext.WorkingLanguage,
- TaxDisplayType = _workContext.TaxDisplayType,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType,
+ Store = _workContextAccessor.WorkContext.CurrentStore
})
: null;
@@ -391,14 +391,14 @@ public class ActionCartController : BasePublicController
//save item
var addToCartWarnings = new List<string>();
var warehouseId = _shoppingCartSettings.AllowToSelectWarehouse ? model.WarehouseId :
- product.UseMultipleWarehouses ? _workContext.CurrentStore.DefaultWarehouseId :
- string.IsNullOrEmpty(_workContext.CurrentStore.DefaultWarehouseId) ? product.WarehouseId :
- _workContext.CurrentStore.DefaultWarehouseId;
+ product.UseMultipleWarehouses ? _workContextAccessor.WorkContext.CurrentStore.DefaultWarehouseId :
+ string.IsNullOrEmpty(_workContextAccessor.WorkContext.CurrentStore.DefaultWarehouseId) ? product.WarehouseId :
+ _workContextAccessor.WorkContext.CurrentStore.DefaultWarehouseId;
//add to the cart
- var (warnings, shoppingCartItem) = await _shoppingCartService.AddToCart(_workContext.CurrentCustomer,
- product.Id, model.ShoppingCartTypeId, _workContext.CurrentStore.Id, warehouseId,
+ var (warnings, shoppingCartItem) = await _shoppingCartService.AddToCart(_workContextAccessor.WorkContext.CurrentCustomer,
+ product.Id, model.ShoppingCartTypeId, _workContextAccessor.WorkContext.CurrentStore.Id, warehouseId,
attributes, customerEnteredPriceConverted,
rentalStartDate, rentalEndDate, model.EnteredQuantity, true, model.Reservation, parameter, duration,
new ShoppingCartValidatorOptions {
@@ -421,16 +421,16 @@ public class ActionCartController : BasePublicController
var addtoCartModel = await _mediator.Send(new GetAddToCart {
Product = product,
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
ShoppingCartItem = shoppingCartItem,
Quantity = model.EnteredQuantity,
CartType = model.ShoppingCartTypeId,
CustomerEnteredPrice = customerEnteredPriceConverted,
Attributes = attributes,
- Currency = _workContext.WorkingCurrency,
- Store = _workContext.CurrentStore,
- Language = _workContext.WorkingLanguage,
- TaxDisplayType = _workContext.TaxDisplayType,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType,
Duration = duration,
Parameter = parameter,
ReservationId = model.Reservation,
@@ -450,7 +450,7 @@ public class ActionCartController : BasePublicController
});
//display notification message and update appropriate blocks
- var qty = (await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var qty = (await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.Wishlist)).Sum(x => x.Quantity);
var updatetopwishlistsectionhtml =
string.Format(_translationService.GetResource("Wishlist.HeaderQuantity"), qty);
@@ -484,17 +484,17 @@ public class ActionCartController : BasePublicController
var updatetopcartsectionhtml = string.Format(
_translationService.GetResource("ShoppingCart.HeaderQuantity"),
- (await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ (await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
shoppingCartTypes.ToArray()))
.Sum(x => x.Quantity));
var miniShoppingCartmodel = _shoppingCartSettings.MiniShoppingCartEnabled
? await _mediator.Send(new GetMiniShoppingCart {
- Customer = _workContext.CurrentCustomer,
- Currency = _workContext.WorkingCurrency,
- Language = _workContext.WorkingLanguage,
- TaxDisplayType = _workContext.TaxDisplayType,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType,
+ Store = _workContextAccessor.WorkContext.CurrentStore
})
: null;
@@ -518,7 +518,7 @@ public class ActionCartController : BasePublicController
[HttpPost]
public virtual async Task<IActionResult> UpdateItemCart(ProductDetailsCart model)
{
- var cart = _workContext.CurrentCustomer.ShoppingCartItems.FirstOrDefault(sci =>
+ var cart = _workContextAccessor.WorkContext.CurrentCustomer.ShoppingCartItems.FirstOrDefault(sci =>
sci.Id == model.ShoppingCartItemId);
if (cart == null)
return Json(new {
@@ -568,7 +568,7 @@ public class ActionCartController : BasePublicController
if (double.TryParse(model.CustomerEnteredPrice, out var customerEnteredPrice))
customerEnteredPriceConverted =
await _currencyService.ConvertToPrimaryStoreCurrency(customerEnteredPrice,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
#endregion
@@ -635,7 +635,7 @@ public class ActionCartController : BasePublicController
var warehouseId = _shoppingCartSettings.AllowToSelectWarehouse ? model.WarehouseId : cart.WarehouseId;
//update existing item
- addToCartWarnings.AddRange(await _shoppingCartService.UpdateShoppingCartItem(_workContext.CurrentCustomer,
+ addToCartWarnings.AddRange(await _shoppingCartService.UpdateShoppingCartItem(_workContextAccessor.WorkContext.CurrentCustomer,
cart.Id, warehouseId, attributes, customerEnteredPriceConverted,
rentalStartDate, rentalEndDate, model.EnteredQuantity));
@@ -655,7 +655,7 @@ public class ActionCartController : BasePublicController
[HttpGet]
public virtual async Task<IActionResult> GetItemCart(string shoppingCartId)
{
- var cart = _workContext.CurrentCustomer.ShoppingCartItems.FirstOrDefault(sci => sci.Id == shoppingCartId);
+ var cart = _workContextAccessor.WorkContext.CurrentCustomer.ShoppingCartItems.FirstOrDefault(sci => sci.Id == shoppingCartId);
if (cart == null)
return Json(new {
success = false,
@@ -687,13 +687,13 @@ public class ActionCartController : BasePublicController
redirect = Url.RouteUrl("HomePage")
});
return Json(new {
- redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) })
+ redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id) })
});
}
//prepare the model
var model = await _mediator.Send(new GetProductDetailsPage {
- Store = _workContext.CurrentStore,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Product = product,
UpdateCartItem = cart
});
@@ -707,7 +707,7 @@ public class ActionCartController : BasePublicController
public virtual async Task<IActionResult> AddBid(AddBidModel model,
[FromServices] IAuctionService auctionService)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
if (!await _groupService.IsRegistered(customer))
return Json(new {
success = false,
@@ -738,7 +738,7 @@ public class ActionCartController : BasePublicController
var warehouseId = _shoppingCartSettings.AllowToSelectWarehouse
? model.WarehouseId
- : _workContext.CurrentStore.DefaultWarehouseId;
+ : _workContextAccessor.WorkContext.CurrentStore.DefaultWarehouseId;
var shoppingCartItem = new ShoppingCartItem {
Attributes = new List<CustomAttribute>(),
@@ -746,7 +746,7 @@ public class ActionCartController : BasePublicController
ProductId = product.Id,
WarehouseId = warehouseId,
ShoppingCartTypeId = ShoppingCartType.Auctions,
- StoreId = _workContext.CurrentStore.Id,
+ StoreId = _workContextAccessor.WorkContext.CurrentStore.Id,
EnteredPrice = bid,
Quantity = 1
};
@@ -766,7 +766,7 @@ public class ActionCartController : BasePublicController
}
//insert new bid
- await auctionService.NewBid(customer, product, _workContext.CurrentStore, _workContext.WorkingLanguage,
+ await auctionService.NewBid(customer, product, _workContextAccessor.WorkContext.CurrentStore, _workContextAccessor.WorkContext.WorkingLanguage,
warehouseId, bid);
var addtoCartModel = await _mediator.Send(new GetAddToCart {
@@ -774,10 +774,10 @@ public class ActionCartController : BasePublicController
Customer = customer,
Quantity = 1,
CartType = ShoppingCartType.Auctions,
- Currency = _workContext.WorkingCurrency,
- Store = _workContext.CurrentStore,
- Language = _workContext.WorkingLanguage,
- TaxDisplayType = _workContext.TaxDisplayType
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType
});
return Json(new {
diff --git a/src/Web/Grand.Web/Controllers/BlogController.cs b/src/Web/Grand.Web/Controllers/BlogController.cs
index 1671c532a..3561642c4 100644
--- a/src/Web/Grand.Web/Controllers/BlogController.cs
+++ b/src/Web/Grand.Web/Controllers/BlogController.cs
@@ -27,14 +27,14 @@ public class BlogController : BasePublicController
IMediator mediator,
IBlogService blogService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
BlogSettings blogSettings)
{
_mediator = mediator;
_blogService = blogService;
_translationService = translationService;
_blogSettings = blogSettings;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
#endregion
@@ -44,7 +44,7 @@ public class BlogController : BasePublicController
private readonly IMediator _mediator;
private readonly IBlogService _blogService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly BlogSettings _blogSettings;
#endregion
@@ -122,7 +122,7 @@ public class BlogController : BasePublicController
return RedirectToRoute("HomePage");
//Store acl
- if (!aclService.Authorize(blogPost, _workContext.CurrentStore.Id))
+ if (!aclService.Authorize(blogPost, _workContextAccessor.WorkContext.CurrentStore.Id))
return InvokeHttp404();
var model = await _mediator.Send(new GetBlogPost { BlogPost = blogPost });
@@ -150,7 +150,7 @@ public class BlogController : BasePublicController
success = false
});
- if (!aclService.Authorize(blogPost, _workContext.CurrentStore.Id))
+ if (!aclService.Authorize(blogPost, _workContextAccessor.WorkContext.CurrentStore.Id))
return Json(new {
success = false
});
@@ -169,7 +169,7 @@ public class BlogController : BasePublicController
blogComment.CommentText,
CreatedOn = HttpContext.RequestServices.GetService<IDateTimeService>()
.ConvertToUserTime(blogComment.CreatedOnUtc, DateTimeKind.Utc),
- CustomerName = _workContext.CurrentCustomer.FormatUserName(HttpContext.RequestServices
+ CustomerName = _workContextAccessor.WorkContext.CurrentCustomer.FormatUserName(HttpContext.RequestServices
.GetService<CustomerSettings>().CustomerNameFormat)
}
});
diff --git a/src/Web/Grand.Web/Controllers/CatalogController.cs b/src/Web/Grand.Web/Controllers/CatalogController.cs
index 448174ee6..956ca76bf 100644
--- a/src/Web/Grand.Web/Controllers/CatalogController.cs
+++ b/src/Web/Grand.Web/Controllers/CatalogController.cs
@@ -33,7 +33,7 @@ public class CatalogController : BasePublicController
ICategoryService categoryService,
IBrandService brandService,
ICollectionService collectionService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
ITranslationService translationService,
IAclService aclService,
@@ -45,7 +45,7 @@ public class CatalogController : BasePublicController
_categoryService = categoryService;
_brandService = brandService;
_collectionService = collectionService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_translationService = translationService;
_aclService = aclService;
@@ -62,7 +62,7 @@ public class CatalogController : BasePublicController
private readonly ICategoryService _categoryService;
private readonly IBrandService _brandService;
private readonly ICollectionService _collectionService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
private readonly ITranslationService _translationService;
private readonly IAclService _aclService;
@@ -96,7 +96,7 @@ public class CatalogController : BasePublicController
if (category == null)
return InvokeHttp404();
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
//Check whether the current user has a "Manage catalog" permission
//It allows him to preview a category before publishing
@@ -108,7 +108,7 @@ public class CatalogController : BasePublicController
return InvokeHttp404();
//Store access
- if (!_aclService.Authorize(category, _workContext.CurrentStore.Id))
+ if (!_aclService.Authorize(category, _workContextAccessor.WorkContext.CurrentStore.Id))
return InvokeHttp404();
//display "edit" (manage) link
@@ -120,10 +120,10 @@ public class CatalogController : BasePublicController
var model = await _mediator.Send(new GetCategory {
Category = category,
Command = command,
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
//layout
@@ -137,9 +137,9 @@ public class CatalogController : BasePublicController
public virtual async Task<IActionResult> CategoryAll(CategoryPagingModel command)
{
var model = await _mediator.Send(new GetCategoryAll {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Command = command
});
return View(model);
@@ -156,7 +156,7 @@ public class CatalogController : BasePublicController
if (brand == null)
return InvokeHttp404();
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
//Check whether the current user has a "Manage catalog" permission
//It allows him to preview a collection before publishing
@@ -168,7 +168,7 @@ public class CatalogController : BasePublicController
return InvokeHttp404();
//Store access
- if (!_aclService.Authorize(brand, _workContext.CurrentStore.Id))
+ if (!_aclService.Authorize(brand, _workContextAccessor.WorkContext.CurrentStore.Id))
return InvokeHttp404();
//display "edit" (manage) link
@@ -179,11 +179,11 @@ public class CatalogController : BasePublicController
//model
var model = await _mediator.Send(new GetBrand {
Command = command,
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
Brand = brand,
- Store = _workContext.CurrentStore
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
//template
@@ -196,9 +196,9 @@ public class CatalogController : BasePublicController
public virtual async Task<IActionResult> BrandAll(BrandPagingModel command)
{
var model = await _mediator.Send(new GetBrandAll {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Command = command
});
return View(model);
@@ -215,7 +215,7 @@ public class CatalogController : BasePublicController
if (collection == null)
return InvokeHttp404();
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
//Check whether the current user has a "Manage catalog" permission
//It allows him to preview a collection before publishing
@@ -228,7 +228,7 @@ public class CatalogController : BasePublicController
return InvokeHttp404();
//Store access
- if (!_aclService.Authorize(collection, _workContext.CurrentStore.Id))
+ if (!_aclService.Authorize(collection, _workContextAccessor.WorkContext.CurrentStore.Id))
return InvokeHttp404();
//display "edit" (manage) link
@@ -239,11 +239,11 @@ public class CatalogController : BasePublicController
//model
var model = await _mediator.Send(new GetCollection {
Command = command,
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
Collection = collection,
- Store = _workContext.CurrentStore
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
//template
@@ -257,9 +257,9 @@ public class CatalogController : BasePublicController
public virtual async Task<IActionResult> CollectionAll(CollectionPagingModel command)
{
var model = await _mediator.Send(new GetCollectionAll {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Command = command
});
return View(model);
@@ -280,7 +280,7 @@ public class CatalogController : BasePublicController
if (!vendor.Active)
return InvokeHttp404();
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
//display "edit" (manage) link
if (await _permissionService.Authorize(StandardPermission.ManageAccessAdminPanel, customer) &&
@@ -290,9 +290,9 @@ public class CatalogController : BasePublicController
var model = await _mediator.Send(new GetVendor {
Command = command,
Vendor = vendor,
- Language = _workContext.WorkingLanguage,
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
//review
model.VendorReviewOverview = PrepareVendorReviewOverviewModel(vendor);
@@ -308,7 +308,7 @@ public class CatalogController : BasePublicController
return RedirectToRoute("HomePage");
var model = await _mediator.Send(
- new GetVendorAll { Language = _workContext.WorkingLanguage, Command = command });
+ new GetVendorAll { Language = _workContextAccessor.WorkContext.WorkingLanguage, Command = command });
return View(model);
}
@@ -329,7 +329,7 @@ public class CatalogController : BasePublicController
if (ModelState.IsValid)
{
var vendorReview = await _mediator.Send(new InsertVendorReviewCommand
- { Vendor = vendor, Store = _workContext.CurrentStore, Model = model });
+ { Vendor = vendor, Store = _workContextAccessor.WorkContext.CurrentStore, Model = model });
//raise event
if (vendorReview.IsApproved)
await _mediator.Publish(new VendorReviewApprovedEvent(vendorReview));
@@ -372,7 +372,7 @@ public class CatalogController : BasePublicController
if (vendorReview == null)
throw new ArgumentException("No vendor review found with the specified id");
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
if (await _groupService.IsGuest(customer) && !_vendorSettings.AllowAnonymousUsersToReviewVendor)
return Json(new {
@@ -390,7 +390,7 @@ public class CatalogController : BasePublicController
});
vendorReview = await _mediator.Send(new SetVendorReviewHelpfulnessCommand {
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
Vendor = vendor,
Review = vendorReview,
Washelpful = washelpful
@@ -417,10 +417,10 @@ public class CatalogController : BasePublicController
var model = await _mediator.Send(new GetProductsByTag {
Command = command,
- Language = _workContext.WorkingLanguage,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
ProductTag = productTag,
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return View(model);
}
@@ -435,10 +435,10 @@ public class CatalogController : BasePublicController
var model = await _mediator.Send(new GetProductsByTag {
Command = command,
- Language = _workContext.WorkingLanguage,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
ProductTag = productTag,
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return View("ProductsByTag", model);
}
@@ -447,8 +447,8 @@ public class CatalogController : BasePublicController
public virtual async Task<IActionResult> ProductTagsAll()
{
var model = await _mediator.Send(new GetProductTagsAll {
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return View(model);
}
@@ -470,12 +470,12 @@ public class CatalogController : BasePublicController
var isSearchTermSpecified = HttpContext.Request.Query.ContainsKey("q");
var searchModel = await _mediator.Send(new GetSearch {
Command = command,
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
IsSearchTermSpecified = isSearchTermSpecified,
- Language = _workContext.WorkingLanguage,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
Model = model,
- Store = _workContext.CurrentStore
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return View(searchModel);
}
@@ -490,10 +490,10 @@ public class CatalogController : BasePublicController
var result = await _mediator.Send(new GetSearchAutoComplete {
CategoryId = categoryId,
Term = term.Trim(),
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore,
- Language = _workContext.WorkingLanguage,
- Currency = _workContext.WorkingCurrency
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency
});
return Json(result);
}
diff --git a/src/Web/Grand.Web/Controllers/CheckoutController.cs b/src/Web/Grand.Web/Controllers/CheckoutController.cs
index 0f17f68c0..8e885a7a6 100644
--- a/src/Web/Grand.Web/Controllers/CheckoutController.cs
+++ b/src/Web/Grand.Web/Controllers/CheckoutController.cs
@@ -35,7 +35,7 @@ public class CheckoutController : BasePublicController
#region Constructors
public CheckoutController(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ITranslationService translationService,
ICustomerService customerService,
IGroupService groupService,
@@ -55,7 +55,7 @@ public class CheckoutController : BasePublicController
ShippingSettings shippingSettings,
AddressSettings addressSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_translationService = translationService;
_customerService = customerService;
_groupService = groupService;
@@ -81,9 +81,9 @@ public class CheckoutController : BasePublicController
[HttpGet]
public virtual async Task<IActionResult> Index()
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.ShoppingCart, ShoppingCartType.Auctions);
if (!cart.Any())
@@ -93,10 +93,10 @@ public class CheckoutController : BasePublicController
return Challenge();
//reset checkout data
- await _customerService.ResetCheckoutData(customer, _workContext.CurrentStore.Id);
+ await _customerService.ResetCheckoutData(customer, _workContextAccessor.WorkContext.CurrentStore.Id);
//validation (cart)
- var checkoutAttributes = customer.GetUserFieldFromEntity<List<CustomAttribute>>(SystemCustomerFieldNames.CheckoutAttributes, _workContext.CurrentStore.Id);
+ var checkoutAttributes = customer.GetUserFieldFromEntity<List<CustomAttribute>>(SystemCustomerFieldNames.CheckoutAttributes, _workContextAccessor.WorkContext.CurrentStore.Id);
var scWarnings = await _shoppingCartValidator.GetShoppingCartWarnings(cart, checkoutAttributes, true, true);
if (scWarnings.Any())
return RedirectToRoute("ShoppingCart", new { checkoutAttributes = true });
@@ -119,20 +119,20 @@ public class CheckoutController : BasePublicController
public virtual async Task<IActionResult> Start()
{
//validation
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.ShoppingCart, ShoppingCartType.Auctions);
if (!cart.Any())
return RedirectToRoute("ShoppingCart");
- if (await _groupService.IsGuest(_workContext.CurrentCustomer) && !_orderSettings.AnonymousCheckoutAllowed)
+ if (await _groupService.IsGuest(_workContextAccessor.WorkContext.CurrentCustomer) && !_orderSettings.AnonymousCheckoutAllowed)
return Challenge();
//validation (each shopping cart item)
foreach (var sci in cart)
{
var product = await _productService.GetProductById(sci.ProductId);
- var sciWarnings = await _shoppingCartValidator.GetShoppingCartItemWarnings(_workContext.CurrentCustomer,
+ var sciWarnings = await _shoppingCartValidator.GetShoppingCartItemWarnings(_workContextAccessor.WorkContext.CurrentCustomer,
sci, product, new ShoppingCartValidatorOptions());
if (sciWarnings.Any())
return RedirectToRoute("ShoppingCart", new { checkoutAttributes = true });
@@ -143,17 +143,17 @@ public class CheckoutController : BasePublicController
ShippingRequired = requiresShipping,
BillingAddress = await _mediator.Send(new GetBillingAddress {
Cart = cart,
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
PrePopulateNewAddressWithCustomerFields = true
}),
ShippingAddress = await _mediator.Send(new GetShippingAddress {
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
PrePopulateNewAddressWithCustomerFields = true
})
};
@@ -171,7 +171,7 @@ public class CheckoutController : BasePublicController
try
{
//validation
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.ShoppingCart, ShoppingCartType.Auctions);
await CartValidate(cart);
@@ -179,10 +179,10 @@ public class CheckoutController : BasePublicController
{
//existing address
var address =
- _workContext.CurrentCustomer.Addresses.FirstOrDefault(a => a.Id == model.BillingAddressId);
- _workContext.CurrentCustomer.BillingAddress =
+ _workContextAccessor.WorkContext.CurrentCustomer.Addresses.FirstOrDefault(a => a.Id == model.BillingAddressId);
+ _workContextAccessor.WorkContext.CurrentCustomer.BillingAddress =
address ?? throw new Exception("Address can't be loaded");
- await _customerService.UpdateBillingAddress(address, _workContext.CurrentCustomer.Id);
+ await _customerService.UpdateBillingAddress(address, _workContextAccessor.WorkContext.CurrentCustomer.Id);
}
else
{
@@ -191,10 +191,10 @@ public class CheckoutController : BasePublicController
//model is not valid. redisplay the form with errors
var billingAddressModel = await _mediator.Send(new GetBillingAddress {
Cart = cart,
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
SelectedCountryId = model.BillingNewAddress.CountryId,
OverrideAttributes = await _mediator.Send(new GetParseCustomAddressAttributes
{ SelectedAttributes = model.BillingNewAddress.SelectedAttributes })
@@ -212,7 +212,7 @@ public class CheckoutController : BasePublicController
}
//try to find an address with the same values (don't duplicate records)
- var address = _workContext.CurrentCustomer.Addresses.ToList().FindAddress(
+ var address = _workContextAccessor.WorkContext.CurrentCustomer.Addresses.ToList().FindAddress(
model.BillingNewAddress.FirstName, model.BillingNewAddress.LastName,
model.BillingNewAddress.PhoneNumber,
model.BillingNewAddress.Email, model.BillingNewAddress.FaxNumber,
@@ -225,32 +225,32 @@ public class CheckoutController : BasePublicController
{
//address is not found. create a new one
address =
- await _groupService.IsGuest(_workContext.CurrentCustomer)
+ await _groupService.IsGuest(_workContextAccessor.WorkContext.CurrentCustomer)
? model.BillingNewAddress.ToEntity()
- : model.BillingNewAddress.ToEntity(_workContext.CurrentCustomer, addressSettings);
+ : model.BillingNewAddress.ToEntity(_workContextAccessor.WorkContext.CurrentCustomer, addressSettings);
address.Attributes = await _mediator.Send(new GetParseCustomAddressAttributes
{ SelectedAttributes = model.BillingNewAddress.SelectedAttributes });
address.AddressType = _addressSettings.AddressTypeEnabled ? AddressType.Billing : AddressType.Any;
- _workContext.CurrentCustomer.Addresses.Add(address);
- await _customerService.InsertAddress(address, _workContext.CurrentCustomer.Id);
+ _workContextAccessor.WorkContext.CurrentCustomer.Addresses.Add(address);
+ await _customerService.InsertAddress(address, _workContextAccessor.WorkContext.CurrentCustomer.Id);
}
- _workContext.CurrentCustomer.BillingAddress = address;
- await _customerService.UpdateBillingAddress(address, _workContext.CurrentCustomer.Id);
+ _workContextAccessor.WorkContext.CurrentCustomer.BillingAddress = address;
+ await _customerService.UpdateBillingAddress(address, _workContextAccessor.WorkContext.CurrentCustomer.Id);
}
//load next step
if (cart.RequiresShipping())
return await LoadStepAfterBillingAddress(cart);
//shipping is not required
- _workContext.CurrentCustomer.ShippingAddress = null;
- await _customerService.UpdateCustomerField(_workContext.CurrentCustomer, x => x.ShippingAddress,
+ _workContextAccessor.WorkContext.CurrentCustomer.ShippingAddress = null;
+ await _customerService.UpdateCustomerField(_workContextAccessor.WorkContext.CurrentCustomer, x => x.ShippingAddress,
null);
- await _customerService.UpdateUserField<ShippingOption>(_workContext.CurrentCustomer,
- SystemCustomerFieldNames.SelectedShippingOption, null, _workContext.CurrentStore.Id);
+ await _customerService.UpdateUserField<ShippingOption>(_workContextAccessor.WorkContext.CurrentCustomer,
+ SystemCustomerFieldNames.SelectedShippingOption, null, _workContextAccessor.WorkContext.CurrentStore.Id);
//load next step
return await LoadStepAfterShippingMethod(cart);
}
@@ -269,7 +269,7 @@ public class CheckoutController : BasePublicController
try
{
//validation
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.ShoppingCart, ShoppingCartType.Auctions);
await CartValidate(cart);
@@ -284,19 +284,19 @@ public class CheckoutController : BasePublicController
{
//customer decided to pick up in store
//no shipping address selected
- _workContext.CurrentCustomer.ShippingAddress = null;
- await _customerService.UpdateCustomerField(_workContext.CurrentCustomer, x => x.ShippingAddress,
+ _workContextAccessor.WorkContext.CurrentCustomer.ShippingAddress = null;
+ await _customerService.UpdateCustomerField(_workContextAccessor.WorkContext.CurrentCustomer, x => x.ShippingAddress,
null);
//clear shipping option XML/Description
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
- SystemCustomerFieldNames.ShippingOptionAttribute, "", _workContext.CurrentStore.Id);
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
+ SystemCustomerFieldNames.ShippingOptionAttribute, "", _workContextAccessor.WorkContext.CurrentStore.Id);
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.ShippingOptionAttributeDescription, "",
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
var pickupPoints =
- await _pickupPointService.LoadActivePickupPoints(_workContext.CurrentStore.Id);
+ await _pickupPointService.LoadActivePickupPoints(_workContextAccessor.WorkContext.CurrentStore.Id);
var selectedPoint = pickupPoints.FirstOrDefault(x => x.Id.Equals(model.PickupPointId));
if (selectedPoint == null)
throw new Exception("Pickup point is not allowed");
@@ -310,21 +310,21 @@ public class CheckoutController : BasePublicController
ShippingRateProviderSystemName = $"PickupPoint_{selectedPoint.Id}"
};
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.SelectedShippingOption,
pickUpInStoreShippingOption,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.SelectedPickupPoint,
selectedPoint.Id,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
}
else
//set value indicating that "pick up in store" option has not been chosen
{
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
- SystemCustomerFieldNames.SelectedPickupPoint, "", _workContext.CurrentStore.Id);
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
+ SystemCustomerFieldNames.SelectedPickupPoint, "", _workContextAccessor.WorkContext.CurrentStore.Id);
}
}
@@ -334,12 +334,12 @@ public class CheckoutController : BasePublicController
{
//existing address
var address =
- _workContext.CurrentCustomer.Addresses.FirstOrDefault(a => a.Id == model.ShippingAddressId);
+ _workContextAccessor.WorkContext.CurrentCustomer.Addresses.FirstOrDefault(a => a.Id == model.ShippingAddressId);
if (address == null)
throw new Exception("Address can't be loaded");
- _workContext.CurrentCustomer.ShippingAddress = address;
- await _customerService.UpdateShippingAddress(address, _workContext.CurrentCustomer.Id);
+ _workContextAccessor.WorkContext.CurrentCustomer.ShippingAddress = address;
+ await _customerService.UpdateShippingAddress(address, _workContextAccessor.WorkContext.CurrentCustomer.Id);
}
else
{
@@ -347,10 +347,10 @@ public class CheckoutController : BasePublicController
{
//model is not valid. redisplay the form with errors
var shippingAddressModel = await _mediator.Send(new GetShippingAddress {
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
SelectedCountryId = model.ShippingNewAddress.CountryId,
OverrideAttributes = await _mediator.Send(new GetParseCustomAddressAttributes
{ SelectedAttributes = model.ShippingNewAddress.SelectedAttributes })
@@ -368,7 +368,7 @@ public class CheckoutController : BasePublicController
}
//try to find an address with the same values (don't duplicate records)
- var address = _workContext.CurrentCustomer.Addresses.ToList().FindAddress(
+ var address = _workContextAccessor.WorkContext.CurrentCustomer.Addresses.ToList().FindAddress(
model.ShippingNewAddress.FirstName, model.ShippingNewAddress.LastName,
model.ShippingNewAddress.PhoneNumber,
model.ShippingNewAddress.Email, model.ShippingNewAddress.FaxNumber,
@@ -380,9 +380,9 @@ public class CheckoutController : BasePublicController
if (address == null)
{
address =
- await _groupService.IsGuest(_workContext.CurrentCustomer)
+ await _groupService.IsGuest(_workContextAccessor.WorkContext.CurrentCustomer)
? model.ShippingNewAddress.ToEntity()
- : model.ShippingNewAddress.ToEntity(_workContext.CurrentCustomer, addressSettings);
+ : model.ShippingNewAddress.ToEntity(_workContextAccessor.WorkContext.CurrentCustomer, addressSettings);
address.Attributes = await _mediator.Send(new GetParseCustomAddressAttributes
{ SelectedAttributes = model.ShippingNewAddress.SelectedAttributes });
@@ -390,32 +390,32 @@ public class CheckoutController : BasePublicController
? model.BillToTheSameAddress ? AddressType.Any : AddressType.Shipping
: AddressType.Any;
//other null validations
- _workContext.CurrentCustomer.Addresses.Add(address);
- await _customerService.InsertAddress(address, _workContext.CurrentCustomer.Id);
+ _workContextAccessor.WorkContext.CurrentCustomer.Addresses.Add(address);
+ await _customerService.InsertAddress(address, _workContextAccessor.WorkContext.CurrentCustomer.Id);
}
- _workContext.CurrentCustomer.ShippingAddress = address;
- await _customerService.UpdateShippingAddress(address, _workContext.CurrentCustomer.Id);
+ _workContextAccessor.WorkContext.CurrentCustomer.ShippingAddress = address;
+ await _customerService.UpdateShippingAddress(address, _workContextAccessor.WorkContext.CurrentCustomer.Id);
}
}
if (model.BillToTheSameAddress && !model.PickUpInStore &&
- _workContext.CurrentCustomer.ShippingAddress!.AddressType != AddressType.Shipping)
+ _workContextAccessor.WorkContext.CurrentCustomer.ShippingAddress!.AddressType != AddressType.Shipping)
{
- _workContext.CurrentCustomer.BillingAddress = _workContext.CurrentCustomer.ShippingAddress;
- await _customerService.UpdateBillingAddress(_workContext.CurrentCustomer.BillingAddress,
- _workContext.CurrentCustomer.Id);
- await _customerService.UpdateUserField<ShippingOption>(_workContext.CurrentCustomer,
- SystemCustomerFieldNames.SelectedShippingOption, null, _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentCustomer.BillingAddress = _workContextAccessor.WorkContext.CurrentCustomer.ShippingAddress;
+ await _customerService.UpdateBillingAddress(_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress,
+ _workContextAccessor.WorkContext.CurrentCustomer.Id);
+ await _customerService.UpdateUserField<ShippingOption>(_workContextAccessor.WorkContext.CurrentCustomer,
+ SystemCustomerFieldNames.SelectedShippingOption, null, _workContextAccessor.WorkContext.CurrentStore.Id);
return await LoadStepAfterBillingAddress(cart);
}
var billingAddressModel = await _mediator.Send(new GetBillingAddress {
Cart = cart,
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
SelectedCountryId = model.ShippingNewAddress.CountryId
});
if (!billingAddressModel.ExistingAddresses.Any())
@@ -442,10 +442,10 @@ public class CheckoutController : BasePublicController
try
{
//validation
- var customer = _workContext.CurrentCustomer;
- var store = _workContext.CurrentStore;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
+ var store = _workContextAccessor.WorkContext.CurrentStore;
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.ShoppingCart, ShoppingCartType.Auctions);
await CartValidate(cart);
@@ -530,7 +530,7 @@ public class CheckoutController : BasePublicController
try
{
//validation
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.ShoppingCart, ShoppingCartType.Auctions);
await CartValidate(cart);
@@ -540,9 +540,9 @@ public class CheckoutController : BasePublicController
//loyalty points
if (_loyaltyPointsSettings.Enabled)
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.UseLoyaltyPointsDuringCheckout, model.UseLoyaltyPoints,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
//Check whether payment workflow is required
var isPaymentWorkflowRequired =
@@ -550,12 +550,12 @@ public class CheckoutController : BasePublicController
if (!isPaymentWorkflowRequired)
{
//payment is not required
- await _customerService.UpdateUserField<string>(_workContext.CurrentCustomer,
- SystemCustomerFieldNames.SelectedPaymentMethod, null, _workContext.CurrentStore.Id);
+ await _customerService.UpdateUserField<string>(_workContextAccessor.WorkContext.CurrentCustomer,
+ SystemCustomerFieldNames.SelectedPaymentMethod, null, _workContextAccessor.WorkContext.CurrentStore.Id);
var confirmOrderModel = await _mediator.Send(new GetConfirmOrder {
- Cart = cart, Customer = _workContext.CurrentCustomer, Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Cart = cart, Customer = _workContextAccessor.WorkContext.CurrentCustomer, Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return Json(new {
update_section = new UpdateSectionJsonModel {
@@ -569,21 +569,21 @@ public class CheckoutController : BasePublicController
var paymentMethodInst = _paymentService.LoadPaymentMethodBySystemName(model.PaymentMethod);
if (paymentMethodInst == null ||
!paymentMethodInst.IsPaymentMethodActive(_paymentSettings) ||
- !paymentMethodInst.IsAuthenticateStore(_workContext.CurrentStore))
+ !paymentMethodInst.IsAuthenticateStore(_workContextAccessor.WorkContext.CurrentStore))
throw new Exception("Selected payment method can't be parsed");
//save
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
- SystemCustomerFieldNames.SelectedPaymentMethod, model.PaymentMethod, _workContext.CurrentStore.Id);
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
+ SystemCustomerFieldNames.SelectedPaymentMethod, model.PaymentMethod, _workContextAccessor.WorkContext.CurrentStore.Id);
var paymentTransaction = await paymentMethodInst.InitPaymentTransaction();
if (paymentTransaction != null)
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.PaymentTransaction, paymentTransaction.Id,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
else
- await _customerService.UpdateUserField<string>(_workContext.CurrentCustomer,
- SystemCustomerFieldNames.PaymentTransaction, null, _workContext.CurrentStore.Id);
+ await _customerService.UpdateUserField<string>(_workContextAccessor.WorkContext.CurrentCustomer,
+ SystemCustomerFieldNames.PaymentTransaction, null, _workContextAccessor.WorkContext.CurrentStore.Id);
return await LoadStepAfterPaymentMethod(paymentMethodInst, cart);
}
@@ -600,11 +600,11 @@ public class CheckoutController : BasePublicController
try
{
//validation
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.ShoppingCart, ShoppingCartType.Auctions);
await CartValidate(cart);
- var paymentMethodSystemName = _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.SelectedPaymentMethod, _workContext.CurrentStore.Id);
+ var paymentMethodSystemName = _workContextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.SelectedPaymentMethod, _workContextAccessor.WorkContext.CurrentStore.Id);
var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(paymentMethodSystemName);
if (paymentMethod == null)
throw new Exception("Payment method is not selected");
@@ -616,13 +616,13 @@ public class CheckoutController : BasePublicController
var paymentTransaction = await paymentMethod.SavePaymentInfo(model);
if (paymentTransaction != null)
//save
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.PaymentTransaction, paymentTransaction.Id,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
var confirmOrderModel = await _mediator.Send(new GetConfirmOrder {
- Cart = cart, Customer = _workContext.CurrentCustomer, Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Cart = cart, Customer = _workContextAccessor.WorkContext.CurrentCustomer, Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return Json(new {
update_section = new UpdateSectionJsonModel {
@@ -654,17 +654,17 @@ public class CheckoutController : BasePublicController
public virtual async Task<IActionResult> Completed(string orderId)
{
//validation
- if (await _groupService.IsGuest(_workContext.CurrentCustomer) && !_orderSettings.AnonymousCheckoutAllowed)
+ if (await _groupService.IsGuest(_workContextAccessor.WorkContext.CurrentCustomer) && !_orderSettings.AnonymousCheckoutAllowed)
return Challenge();
Order order = null;
if (!string.IsNullOrEmpty(orderId)) order = await _orderService.GetOrderById(orderId);
- order ??= (await _orderService.SearchOrders(_workContext.CurrentStore.Id,
- customerId: _workContext.CurrentCustomer.Id, pageSize: 1))
+ order ??= (await _orderService.SearchOrders(_workContextAccessor.WorkContext.CurrentStore.Id,
+ customerId: _workContextAccessor.WorkContext.CurrentCustomer.Id, pageSize: 1))
.FirstOrDefault();
- if (order == null || order.Deleted || _workContext.CurrentCustomer.Id != order.CustomerId)
+ if (order == null || order.Deleted || _workContextAccessor.WorkContext.CurrentCustomer.Id != order.CustomerId)
return RedirectToRoute("HomePage");
//disable "order completed" page?
@@ -687,14 +687,14 @@ public class CheckoutController : BasePublicController
try
{
//validation
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.ShoppingCart, ShoppingCartType.Auctions);
await CartValidate(cart);
//prevent 2 orders being placed within an X seconds time frame
if (!await _mediator.Send(new GetMinOrderPlaceIntervalValid {
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore
}))
return Json(new {
error = 1, message = _translationService.GetResource("Checkout.MinOrderPlacementInterval")
@@ -714,7 +714,7 @@ public class CheckoutController : BasePublicController
if (paymentMethod.PaymentMethodType == PaymentMethodType.Redirection)
{
//Redirection will not work because it's AJAX request.
- var storeLocation = _workContext.CurrentHost.Url.TrimEnd('/');
+ var storeLocation = _workContextAccessor.WorkContext.CurrentHost.Url.TrimEnd('/');
//redirect
return Json(new {
redirect =
@@ -729,8 +729,8 @@ public class CheckoutController : BasePublicController
//error
var confirmOrderModel = await _mediator.Send(new GetConfirmOrder {
- Cart = cart, Customer = _workContext.CurrentCustomer, Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Cart = cart, Customer = _workContextAccessor.WorkContext.CurrentCustomer, Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
foreach (var error in placeOrderResult.Errors)
confirmOrderModel.Warnings.Add(error);
@@ -755,7 +755,7 @@ public class CheckoutController : BasePublicController
{
try
{
- if (await _groupService.IsGuest(_workContext.CurrentCustomer) &&
+ if (await _groupService.IsGuest(_workContextAccessor.WorkContext.CurrentCustomer) &&
!_orderSettings.AnonymousCheckoutAllowed)
return Challenge();
@@ -797,7 +797,7 @@ public class CheckoutController : BasePublicController
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ITranslationService _translationService;
private readonly ICustomerService _customerService;
private readonly IGroupService _groupService;
@@ -857,7 +857,7 @@ public class CheckoutController : BasePublicController
if (!cart.Any())
throw new Exception("Your cart is empty");
- if (await _groupService.IsGuest(_workContext.CurrentCustomer) && !_orderSettings.AnonymousCheckoutAllowed)
+ if (await _groupService.IsGuest(_workContextAccessor.WorkContext.CurrentCustomer) && !_orderSettings.AnonymousCheckoutAllowed)
throw new Exception("Anonymous checkout is not allowed");
}
@@ -866,16 +866,16 @@ public class CheckoutController : BasePublicController
{
var shippingMethodModel = await _mediator.Send(new GetShippingMethod {
Cart = cart,
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- ShippingAddress = _workContext.CurrentCustomer.ShippingAddress,
- Store = _workContext.CurrentStore
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ ShippingAddress = _workContextAccessor.WorkContext.CurrentCustomer.ShippingAddress,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
var selectedPickupPoint =
- _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(
- SystemCustomerFieldNames.SelectedPickupPoint, _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<string>(
+ SystemCustomerFieldNames.SelectedPickupPoint, _workContextAccessor.WorkContext.CurrentStore.Id);
if ((!_shippingSettings.SkipShippingMethodSelectionIfOnlyOne ||
shippingMethodModel.ShippingMethods.Count != 1) &&
@@ -888,10 +888,10 @@ public class CheckoutController : BasePublicController
goto_section = "shipping_method"
});
if (!(_shippingSettings.AllowPickUpInStore && !string.IsNullOrEmpty(selectedPickupPoint)))
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.SelectedShippingOption,
shippingMethodModel.ShippingMethods.First().ShippingOption,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentStore.Id);
//load next step
return await LoadStepAfterShippingMethod(cart);
@@ -909,18 +909,18 @@ public class CheckoutController : BasePublicController
//filter by country
var filterByCountryId = "";
if (_addressSettings.CountryEnabled &&
- _workContext.CurrentCustomer.BillingAddress != null &&
- !string.IsNullOrEmpty(_workContext.CurrentCustomer.BillingAddress.CountryId))
- filterByCountryId = _workContext.CurrentCustomer.BillingAddress.CountryId;
+ _workContextAccessor.WorkContext.CurrentCustomer.BillingAddress != null &&
+ !string.IsNullOrEmpty(_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress.CountryId))
+ filterByCountryId = _workContextAccessor.WorkContext.CurrentCustomer.BillingAddress.CountryId;
//payment is required
var paymentMethodModel = await _mediator.Send(new GetPaymentMethod {
Cart = cart,
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
FilterByCountryId = filterByCountryId,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
if (!_paymentSettings.SkipPaymentIfOnlyOne ||
@@ -936,15 +936,15 @@ public class CheckoutController : BasePublicController
//so customer doesn't have to choose a payment method
var selectedPaymentMethodSystemName = paymentMethodModel.PaymentMethods[0].PaymentMethodSystemName;
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.SelectedPaymentMethod,
- selectedPaymentMethodSystemName, _workContext.CurrentStore.Id);
+ selectedPaymentMethodSystemName, _workContextAccessor.WorkContext.CurrentStore.Id);
var paymentMethodInst =
_paymentService.LoadPaymentMethodBySystemName(selectedPaymentMethodSystemName);
if (paymentMethodInst == null ||
!paymentMethodInst.IsPaymentMethodActive(_paymentSettings) ||
- !paymentMethodInst.IsAuthenticateStore(_workContext.CurrentStore))
+ !paymentMethodInst.IsAuthenticateStore(_workContextAccessor.WorkContext.CurrentStore))
throw new Exception("Selected payment method can't be parsed");
return await LoadStepAfterPaymentMethod(paymentMethodInst, cart);
@@ -953,12 +953,12 @@ public class CheckoutController : BasePublicController
}
//payment is not required
- await _customerService.UpdateUserField<string>(_workContext.CurrentCustomer,
- SystemCustomerFieldNames.SelectedPaymentMethod, null, _workContext.CurrentStore.Id);
+ await _customerService.UpdateUserField<string>(_workContextAccessor.WorkContext.CurrentCustomer,
+ SystemCustomerFieldNames.SelectedPaymentMethod, null, _workContextAccessor.WorkContext.CurrentStore.Id);
var confirmOrderModel = await _mediator.Send(new GetConfirmOrder {
- Cart = cart, Customer = _workContext.CurrentCustomer, Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Cart = cart, Customer = _workContextAccessor.WorkContext.CurrentCustomer, Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return Json(new {
update_section = new UpdateSectionJsonModel {
@@ -978,8 +978,8 @@ public class CheckoutController : BasePublicController
&& _paymentSettings.SkipPaymentInfo))
{
var confirmOrderModel = await _mediator.Send(new GetConfirmOrder {
- Cart = cart, Customer = _workContext.CurrentCustomer, Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Cart = cart, Customer = _workContextAccessor.WorkContext.CurrentCustomer, Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return Json(new {
update_section = new UpdateSectionJsonModel {
diff --git a/src/Web/Grand.Web/Controllers/CommonController.cs b/src/Web/Grand.Web/Controllers/CommonController.cs
index 080c23cda..408fda09b 100644
--- a/src/Web/Grand.Web/Controllers/CommonController.cs
+++ b/src/Web/Grand.Web/Controllers/CommonController.cs
@@ -1,4 +1,5 @@
-using Grand.Business.Core.Interfaces.Cms;
+using Grand.Business.Common.Services.Stores;
+using Grand.Business.Core.Interfaces.Cms;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Stores;
@@ -12,6 +13,7 @@ using Grand.Domain.Tax;
using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
using Grand.SharedKernel.Attributes;
+using Grand.SharedKernel.Extensions;
using Grand.Web.Commands.Models.Customers;
using Grand.Web.Common.Controllers;
using Grand.Web.Common.Filters;
@@ -31,11 +33,11 @@ public class CommonController : BasePublicController
{
#region Constructors
- public CommonController(IWorkContext workContext,
+ public CommonController(IWorkContextAccessor workContextAccessor,
ILanguageService languageService,
IMediator mediator)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_languageService = languageService;
_mediator = mediator;
}
@@ -45,7 +47,7 @@ public class CommonController : BasePublicController
#region Fields
private readonly ILanguageService _languageService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
#endregion
@@ -149,7 +151,7 @@ public class CommonController : BasePublicController
{
var language = await _languageService.GetLanguageByCode(langCode);
if (!language?.Published ?? false)
- language = _workContext.WorkingLanguage;
+ language = _workContextAccessor.WorkContext.WorkingLanguage;
//prevent open redirection attack
if (!Url.IsLocalUrl(returnUrl))
@@ -163,10 +165,10 @@ public class CommonController : BasePublicController
returnUrl = AddLanguageSeo(returnUrl, language);
}
- await customerService.UpdateUserField(_workContext.CurrentCustomer, SystemCustomerFieldNames.LanguageId, language.Id, _workContext.CurrentStore.Id);
+ await customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.LanguageId, language.Id, _workContextAccessor.WorkContext.CurrentStore.Id);
//notification
- await _mediator.Publish(new ChangeLanguageEvent(_workContext.CurrentCustomer, language));
+ await _mediator.Publish(new ChangeLanguageEvent(_workContextAccessor.WorkContext.CurrentCustomer, language));
return Redirect(returnUrl);
}
@@ -213,17 +215,17 @@ public class CommonController : BasePublicController
{
var currency = await currencyService.GetCurrencyByCode(currencyCode);
if (currency != null)
- await customerService.UpdateUserField(_workContext.CurrentCustomer, SystemCustomerFieldNames.CurrencyId,
- currency.Id, _workContext.CurrentStore.Id);
+ await customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.CurrencyId,
+ currency.Id, _workContextAccessor.WorkContext.CurrentStore.Id);
//clear coupon code
- await customerService.UpdateUserField(_workContext.CurrentCustomer, SystemCustomerFieldNames.DiscountCoupons, "");
+ await customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.DiscountCoupons, "");
//clear gift card
- await customerService.UpdateUserField(_workContext.CurrentCustomer, SystemCustomerFieldNames.GiftVoucherCoupons, "");
+ await customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.GiftVoucherCoupons, "");
//notification
- await _mediator.Publish(new ChangeCurrencyEvent(_workContext.CurrentCustomer, currency));
+ await _mediator.Publish(new ChangeCurrencyEvent(_workContextAccessor.WorkContext.CurrentCustomer, currency));
//prevent open redirection attack
if (!Url.IsLocalUrl(returnUrl))
@@ -238,24 +240,24 @@ public class CommonController : BasePublicController
[HttpGet]
public virtual async Task<IActionResult> SetStore(
[FromServices] IStoreService storeService,
- [FromServices] IStoreHelper storeHelper,
[FromServices] CommonSettings commonSettings,
+ [FromServices] SecurityConfig securityConfig,
string shortcut, string returnUrl = "")
{
- var currentstoreShortcut = _workContext.CurrentStore.Shortcut;
+ var currentstoreShortcut = _workContextAccessor.WorkContext.CurrentStore.Shortcut;
if (currentstoreShortcut != shortcut)
if (commonSettings.AllowToSelectStore)
{
- var selectedstore = storeService.GetAll().FirstOrDefault(x =>
+ var selectedstore = (await storeService.GetAllStores()).FirstOrDefault(x =>
string.Equals(x.Shortcut, shortcut, StringComparison.InvariantCultureIgnoreCase));
if (selectedstore != null)
{
- await storeHelper.SetStoreCookie(selectedstore.Id);
+ SetStoreCookie(selectedstore);
//notification
- await _mediator.Publish(new ChangeStoreEvent(_workContext.CurrentCustomer, selectedstore));
+ await _mediator.Publish(new ChangeStoreEvent(_workContextAccessor.WorkContext.CurrentCustomer, selectedstore));
- if (selectedstore.Url != _workContext.CurrentStore.Url)
+ if (selectedstore.Url != _workContextAccessor.WorkContext.CurrentStore.Url)
return Redirect(selectedstore.SslEnabled ? selectedstore.SecureUrl : selectedstore.Url);
}
}
@@ -265,6 +267,25 @@ public class CommonController : BasePublicController
returnUrl = Url.RouteUrl("HomePage");
return Redirect(returnUrl);
+
+ void SetStoreCookie(Store store)
+ {
+ if (store == null)
+ return;
+
+ //remove current cookie
+ HttpContext.Response.Cookies.Delete(CommonHelper.StoreCookieName);
+
+ //get date of cookie expiration
+ var cookieExpiresDate = DateTime.UtcNow.AddHours(securityConfig.CookieAuthExpires);
+
+ //set new cookie value
+ var options = new CookieOptions {
+ HttpOnly = true,
+ Expires = cookieExpiresDate
+ };
+ HttpContext.Response.Cookies.Append(CommonHelper.StoreCookieName, store.Id, options);
+ }
}
[DenySystemAccount]
@@ -287,11 +308,11 @@ public class CommonController : BasePublicController
return Redirect(returnUrl);
//save passed value
- await customerService.UpdateUserField(_workContext.CurrentCustomer,
- SystemCustomerFieldNames.TaxDisplayTypeId, (int)taxDisplayType, _workContext.CurrentStore.Id);
+ await customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
+ SystemCustomerFieldNames.TaxDisplayTypeId, (int)taxDisplayType, _workContextAccessor.WorkContext.CurrentStore.Id);
//notification
- await _mediator.Publish(new ChangeTaxTypeEvent(_workContext.CurrentCustomer, taxDisplayType));
+ await _mediator.Publish(new ChangeTaxTypeEvent(_workContextAccessor.WorkContext.CurrentCustomer, taxDisplayType));
return Redirect(returnUrl);
}
@@ -312,7 +333,7 @@ public class CommonController : BasePublicController
if (themeContext != null) await themeContext.SetTheme(themeName);
//notification
- await _mediator.Publish(new ChangeThemeEvent(_workContext.CurrentCustomer, themeName));
+ await _mediator.Publish(new ChangeThemeEvent(_workContextAccessor.WorkContext.CurrentCustomer, themeName));
return Redirect(returnUrl);
}
@@ -325,9 +346,9 @@ public class CommonController : BasePublicController
return RedirectToRoute("HomePage");
var model = await _mediator.Send(new GetSitemap {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return View(model);
}
@@ -346,18 +367,18 @@ public class CommonController : BasePublicController
return Json(new { stored = false });
//save consent cookies
- await customerService.UpdateUserField(_workContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies, "",
- _workContext.CurrentStore.Id);
+ await customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies, "",
+ _workContextAccessor.WorkContext.CurrentStore.Id);
var consentCookies = cookiePreference.GetConsentCookies();
var dictionary = consentCookies.Where(x => x.AllowToDisable).ToDictionary(item => item.SystemName, item => accept);
if (dictionary.Any())
- await customerService.UpdateUserField(_workContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies,
- dictionary, _workContext.CurrentStore.Id);
+ await customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies,
+ dictionary, _workContextAccessor.WorkContext.CurrentStore.Id);
//save setting - CookieAccepted
- await customerService.UpdateUserField(_workContext.CurrentCustomer, SystemCustomerFieldNames.CookieAccepted,
- true, _workContext.CurrentStore.Id);
+ await customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.CookieAccepted,
+ true, _workContextAccessor.WorkContext.CurrentStore.Id);
return Json(new { stored = true });
}
@@ -373,8 +394,8 @@ public class CommonController : BasePublicController
return Json(new { html = "" });
var model = await _mediator.Send(new GetPrivacyPreference {
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return Json(new
@@ -397,8 +418,8 @@ public class CommonController : BasePublicController
return Json(new { success = false });
const string consent = "ConsentCookies";
- await customerService.UpdateUserField(_workContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies, "",
- _workContext.CurrentStore.Id);
+ await customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies, "",
+ _workContextAccessor.WorkContext.CurrentStore.Id);
var selectedConsentCookies = new List<string>();
foreach (var item in model)
if (item.Key.StartsWith(consent))
@@ -410,7 +431,7 @@ public class CommonController : BasePublicController
if (item.AllowToDisable)
dictionary.Add(item.SystemName, selectedConsentCookies.Contains(item.SystemName));
- await customerService.UpdateUserField(_workContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies, dictionary, _workContext.CurrentStore.Id);
+ await customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer, SystemCustomerFieldNames.ConsentCookies, dictionary, _workContextAccessor.WorkContext.CurrentStore.Id);
return Json(new { success = true });
}
@@ -421,7 +442,7 @@ public class CommonController : BasePublicController
[HttpGet]
public virtual async Task<IActionResult> RobotsTextFile()
{
- var sb = await _mediator.Send(new GetRobotsTextFile { StoreId = _workContext.CurrentStore.Id });
+ var sb = await _mediator.Send(new GetRobotsTextFile { StoreId = _workContextAccessor.WorkContext.CurrentStore.Id });
return Content(sb, "text/plain");
}
@@ -453,7 +474,7 @@ public class CommonController : BasePublicController
if (!customerSettings.GeoEnabled)
return Content("");
- await _mediator.Send(new CurrentPositionCommand { Customer = _workContext.CurrentCustomer, Model = model });
+ await _mediator.Send(new CurrentPositionCommand { Customer = _workContextAccessor.WorkContext.CurrentCustomer, Model = model });
return Content("");
}
diff --git a/src/Web/Grand.Web/Controllers/ContactController.cs b/src/Web/Grand.Web/Controllers/ContactController.cs
index ddeae1c73..38cc5ecc6 100644
--- a/src/Web/Grand.Web/Controllers/ContactController.cs
+++ b/src/Web/Grand.Web/Controllers/ContactController.cs
@@ -24,11 +24,11 @@ public class ContactController : BasePublicController
public ContactController(
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator)
{
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
}
@@ -50,9 +50,9 @@ public class ContactController : BasePublicController
}
var model = await _mediator.Send(new ContactUsCommand {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return View(model);
}
@@ -82,15 +82,15 @@ public class ContactController : BasePublicController
});
//notification
- await _mediator.Publish(new ContactUsEvent(_workContext.CurrentCustomer, result));
+ await _mediator.Publish(new ContactUsEvent(_workContextAccessor.WorkContext.CurrentCustomer, result));
return View(result);
}
var modelReturn = await _mediator.Send(new ContactUsCommand {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Model = model
});
@@ -103,8 +103,8 @@ public class ContactController : BasePublicController
{
var result = await _mediator.Send(new ContactAttributeChangeCommand {
Attributes = model.Attributes,
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return Json(new {
enabledattributeids = result.enabledAttributeIds.ToArray(),
@@ -176,7 +176,7 @@ public class ContactController : BasePublicController
var download = new Download {
DownloadGuid = Guid.NewGuid(),
- CustomerId = _workContext.CurrentCustomer.Id,
+ CustomerId = _workContextAccessor.WorkContext.CurrentCustomer.Id,
UseDownloadUrl = false,
DownloadUrl = "",
DownloadBinary = fileBinary,
@@ -202,7 +202,7 @@ public class ContactController : BasePublicController
#region Fields
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IMediator _mediator;
#endregion
diff --git a/src/Web/Grand.Web/Controllers/CourseController.cs b/src/Web/Grand.Web/Controllers/CourseController.cs
index 46f679fab..8345b6060 100644
--- a/src/Web/Grand.Web/Controllers/CourseController.cs
+++ b/src/Web/Grand.Web/Controllers/CourseController.cs
@@ -26,12 +26,12 @@ public class CourseController : BasePublicController
private readonly IMediator _mediator;
private readonly IPermissionService _permissionService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public CourseController(
IPermissionService permissionService,
IAclService aclService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
ITranslationService translationService,
ICourseService courseService,
@@ -42,7 +42,7 @@ public class CourseController : BasePublicController
{
_permissionService = permissionService;
_aclService = aclService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_translationService = translationService;
_courseService = courseService;
@@ -70,13 +70,13 @@ public class CourseController : BasePublicController
//ACL (access control list)
return _aclService.Authorize(course, customer) &&
//Store access
- _aclService.Authorize(course, _workContext.CurrentStore.Id);
+ _aclService.Authorize(course, _workContextAccessor.WorkContext.CurrentStore.Id);
}
[HttpGet]
public virtual async Task<IActionResult> Details(string courseId)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var course = await _courseService.GetById(courseId);
if (course == null)
@@ -93,8 +93,8 @@ public class CourseController : BasePublicController
//model
var model = await _mediator.Send(new GetCourse {
Course = course,
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage
});
return View(model);
@@ -103,7 +103,7 @@ public class CourseController : BasePublicController
[HttpGet]
public virtual async Task<IActionResult> Lesson(string id)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var lesson = await _courseLessonService.GetById(id);
if (lesson == null)
@@ -124,8 +124,8 @@ public class CourseController : BasePublicController
//model
var model = await _mediator.Send(new GetLesson {
Course = course,
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
Lesson = lesson
});
@@ -135,7 +135,7 @@ public class CourseController : BasePublicController
[HttpGet]
public virtual async Task<IActionResult> DownloadFile(string id)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var lesson = await _courseLessonService.GetById(id);
if (lesson == null || string.IsNullOrEmpty(lesson.AttachmentId))
@@ -171,7 +171,7 @@ public class CourseController : BasePublicController
[HttpGet]
public virtual async Task<IActionResult> VideoFile(string id)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var lesson = await _courseLessonService.GetById(id);
if (lesson == null || string.IsNullOrEmpty(lesson.VideoFile))
@@ -207,7 +207,7 @@ public class CourseController : BasePublicController
[HttpGet]
public virtual async Task<IActionResult> Approved(string id)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var lesson = await _courseLessonService.GetById(id);
if (lesson == null)
@@ -221,7 +221,7 @@ public class CourseController : BasePublicController
return Json(new { result = false });
await _mediator.Send(new CourseLessonApprovedCommand
- { Course = course, Lesson = lesson, Customer = _workContext.CurrentCustomer });
+ { Course = course, Lesson = lesson, Customer = _workContextAccessor.WorkContext.CurrentCustomer });
return Json(new { result = true });
}
diff --git a/src/Web/Grand.Web/Controllers/DownloadController.cs b/src/Web/Grand.Web/Controllers/DownloadController.cs
index 11b8f299e..3f27f7911 100644
--- a/src/Web/Grand.Web/Controllers/DownloadController.cs
+++ b/src/Web/Grand.Web/Controllers/DownloadController.cs
@@ -27,13 +27,13 @@ public class DownloadController : BasePublicController
private readonly IOrderService _orderService;
private readonly IProductService _productService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public DownloadController(IDownloadService downloadService,
IProductService productService,
IOrderService orderService,
IMerchandiseReturnService merchandiseReturnService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ITranslationService translationService,
CustomerSettings customerSettings)
{
@@ -41,7 +41,7 @@ public class DownloadController : BasePublicController
_productService = productService;
_orderService = orderService;
_merchandiseReturnService = merchandiseReturnService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_translationService = translationService;
_customerSettings = customerSettings;
}
@@ -88,10 +88,10 @@ public class DownloadController : BasePublicController
if (_customerSettings.DownloadableProductsValidateUser)
{
- if (_workContext.CurrentCustomer == null)
+ if (_workContextAccessor.WorkContext.CurrentCustomer == null)
return Challenge();
- if (order.CustomerId != _workContext.CurrentCustomer.Id && order.OwnerId != _workContext.CurrentCustomer.Id)
+ if (order.CustomerId != _workContextAccessor.WorkContext.CurrentCustomer.Id && order.OwnerId != _workContextAccessor.WorkContext.CurrentCustomer.Id)
return Content("This is not your order");
}
@@ -192,7 +192,7 @@ public class DownloadController : BasePublicController
return Content("Downloads are not allowed");
if (_customerSettings.DownloadableProductsValidateUser)
- if (order.CustomerId != _workContext.CurrentCustomer.Id && order.OwnerId != _workContext.CurrentCustomer.Id)
+ if (order.CustomerId != _workContextAccessor.WorkContext.CurrentCustomer.Id && order.OwnerId != _workContextAccessor.WorkContext.CurrentCustomer.Id)
return Challenge();
var download = await _downloadService.GetDownloadById(!string.IsNullOrEmpty(orderItem.LicenseDownloadId)
@@ -224,7 +224,7 @@ public class DownloadController : BasePublicController
if (download == null)
return Content("Download is not available any more.");
- if (_workContext.CurrentCustomer == null || download.CustomerId != _workContext.CurrentCustomer.Id)
+ if (_workContextAccessor.WorkContext.CurrentCustomer == null || download.CustomerId != _workContextAccessor.WorkContext.CurrentCustomer.Id)
return Challenge();
if (download.UseDownloadUrl)
@@ -254,8 +254,8 @@ public class DownloadController : BasePublicController
if (order == null)
return InvokeHttp404();
- if (_workContext.CurrentCustomer == null || (order.CustomerId != _workContext.CurrentCustomer.Id &&
- order.OwnerId != _workContext.CurrentCustomer.Id))
+ if (_workContextAccessor.WorkContext.CurrentCustomer == null || (order.CustomerId != _workContextAccessor.WorkContext.CurrentCustomer.Id &&
+ order.OwnerId != _workContextAccessor.WorkContext.CurrentCustomer.Id))
return Challenge();
var download = await _downloadService.GetDownloadById(orderNote.DownloadId);
@@ -294,8 +294,8 @@ public class DownloadController : BasePublicController
if (order == null)
return InvokeHttp404();
- if (_workContext.CurrentCustomer == null || (order.CustomerId != _workContext.CurrentCustomer.Id &&
- order.OwnerId != _workContext.CurrentCustomer.Id))
+ if (_workContextAccessor.WorkContext.CurrentCustomer == null || (order.CustomerId != _workContextAccessor.WorkContext.CurrentCustomer.Id &&
+ order.OwnerId != _workContextAccessor.WorkContext.CurrentCustomer.Id))
return Challenge();
var download = await _downloadService.GetDownloadById(shipmentNote.DownloadId);
@@ -329,7 +329,7 @@ public class DownloadController : BasePublicController
if (customerNote == null)
return InvokeHttp404();
- if (_workContext.CurrentCustomer == null || customerNote.CustomerId != _workContext.CurrentCustomer.Id)
+ if (_workContextAccessor.WorkContext.CurrentCustomer == null || customerNote.CustomerId != _workContextAccessor.WorkContext.CurrentCustomer.Id)
return Challenge();
var download = await _downloadService.GetDownloadById(customerNote.DownloadId);
@@ -364,7 +364,7 @@ public class DownloadController : BasePublicController
if (merchandiseReturn == null)
return InvokeHttp404();
- if (_workContext.CurrentCustomer == null || merchandiseReturn.CustomerId != _workContext.CurrentCustomer.Id)
+ if (_workContextAccessor.WorkContext.CurrentCustomer == null || merchandiseReturn.CustomerId != _workContextAccessor.WorkContext.CurrentCustomer.Id)
return Challenge();
var download = await _downloadService.GetDownloadById(merchandiseReturnNote.DownloadId);
@@ -398,7 +398,7 @@ public class DownloadController : BasePublicController
if (document is not { Published: true })
return InvokeHttp404();
- if (_workContext.CurrentCustomer == null || document.CustomerId != _workContext.CurrentCustomer.Id)
+ if (_workContextAccessor.WorkContext.CurrentCustomer == null || document.CustomerId != _workContextAccessor.WorkContext.CurrentCustomer.Id)
return Challenge();
var download = await _downloadService.GetDownloadById(document.DownloadId);
diff --git a/src/Web/Grand.Web/Controllers/KnowledgebaseController.cs b/src/Web/Grand.Web/Controllers/KnowledgebaseController.cs
index c4edd8141..2623d09b9 100644
--- a/src/Web/Grand.Web/Controllers/KnowledgebaseController.cs
+++ b/src/Web/Grand.Web/Controllers/KnowledgebaseController.cs
@@ -34,12 +34,12 @@ public class KnowledgebaseController : BasePublicController
private readonly IMessageProviderService _messageProviderService;
private readonly IPermissionService _permissionService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public KnowledgebaseController(
KnowledgebaseSettings knowledgebaseSettings,
IKnowledgebaseService knowledgebaseService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ICacheBase cacheBase,
IAclService aclService,
ITranslationService translationService,
@@ -52,7 +52,7 @@ public class KnowledgebaseController : BasePublicController
{
_knowledgebaseSettings = knowledgebaseSettings;
_knowledgebaseService = knowledgebaseService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_cacheBase = cacheBase;
_aclService = aclService;
_translationService = translationService;
@@ -88,38 +88,38 @@ public class KnowledgebaseController : BasePublicController
var model = new KnowledgebaseHomePageModel();
var articles = await _knowledgebaseService.GetPublicKnowledgebaseArticlesByCategory(categoryId);
articles.ForEach(x => model.Items.Add(new KnowledgebaseItemModel {
- Name = x.GetTranslation(y => y.Name, _workContext.WorkingLanguage.Id),
+ Name = x.GetTranslation(y => y.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
Id = x.Id,
- SeName = x.GetTranslation(y => y.SeName, _workContext.WorkingLanguage.Id),
+ SeName = x.GetTranslation(y => y.SeName, _workContextAccessor.WorkContext.WorkingLanguage.Id),
IsArticle = true
}));
//display "edit" (manage) link
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
if (await _permissionService.Authorize(StandardPermission.ManageAccessAdminPanel, customer) &&
await _permissionService.Authorize(StandardPermission.ManageKnowledgebase, customer))
DisplayEditLink(Url.Action("EditCategory", "Knowledgebase", new { id = categoryId, area = "Admin" }));
model.CurrentCategoryId = categoryId;
- model.CurrentCategoryDescription = category.GetTranslation(y => y.Description, _workContext.WorkingLanguage.Id);
+ model.CurrentCategoryDescription = category.GetTranslation(y => y.Description, _workContextAccessor.WorkContext.WorkingLanguage.Id);
model.CurrentCategoryMetaDescription =
- category.GetTranslation(y => y.MetaDescription, _workContext.WorkingLanguage.Id);
+ category.GetTranslation(y => y.MetaDescription, _workContextAccessor.WorkContext.WorkingLanguage.Id);
model.CurrentCategoryMetaKeywords =
- category.GetTranslation(y => y.MetaKeywords, _workContext.WorkingLanguage.Id);
- model.CurrentCategoryMetaTitle = category.GetTranslation(y => y.MetaTitle, _workContext.WorkingLanguage.Id);
- model.CurrentCategoryName = category.GetTranslation(y => y.Name, _workContext.WorkingLanguage.Id);
- model.CurrentCategorySeName = category.GetTranslation(y => y.SeName, _workContext.WorkingLanguage.Id);
+ category.GetTranslation(y => y.MetaKeywords, _workContextAccessor.WorkContext.WorkingLanguage.Id);
+ model.CurrentCategoryMetaTitle = category.GetTranslation(y => y.MetaTitle, _workContextAccessor.WorkContext.WorkingLanguage.Id);
+ model.CurrentCategoryName = category.GetTranslation(y => y.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id);
+ model.CurrentCategorySeName = category.GetTranslation(y => y.SeName, _workContextAccessor.WorkContext.WorkingLanguage.Id);
var breadcrumbCacheKey = string.Format(CacheKeyConst.KNOWLEDGEBASE_CATEGORY_BREADCRUMB_KEY, category.Id,
- string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()), _workContext.CurrentStore.Id,
- _workContext.WorkingLanguage.Id);
+ string.Join(",", _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()), _workContextAccessor.WorkContext.CurrentStore.Id,
+ _workContextAccessor.WorkContext.WorkingLanguage.Id);
model.CategoryBreadcrumb = await _cacheBase.GetAsync(breadcrumbCacheKey, async () =>
(await GetCategoryBreadCrumb(category))
.Select(catBr => new KnowledgebaseCategoryModel {
Id = catBr.Id,
- Name = catBr.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- SeName = catBr.GetSeName(_workContext.WorkingLanguage.Id)
+ Name = catBr.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ SeName = catBr.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id)
})
.ToList()
);
@@ -140,9 +140,9 @@ public class KnowledgebaseController : BasePublicController
var categories = await _knowledgebaseService.GetPublicKnowledgebaseCategoriesByKeyword(keyword);
var allCategories = await _knowledgebaseService.GetPublicKnowledgebaseCategories();
categories.ForEach(x => model.Items.Add(new KnowledgebaseItemModel {
- Name = x.GetTranslation(y => y.Name, _workContext.WorkingLanguage.Id),
+ Name = x.GetTranslation(y => y.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
Id = x.Id,
- SeName = x.GetTranslation(y => y.SeName, _workContext.WorkingLanguage.Id),
+ SeName = x.GetTranslation(y => y.SeName, _workContextAccessor.WorkContext.WorkingLanguage.Id),
IsArticle = false,
FormattedBreadcrumbs = x.GetFormattedBreadCrumb(allCategories, ">")
}));
@@ -151,14 +151,14 @@ public class KnowledgebaseController : BasePublicController
foreach (var item in articles)
{
var kbm = new KnowledgebaseItemModel {
- Name = item.GetTranslation(y => y.Name, _workContext.WorkingLanguage.Id),
+ Name = item.GetTranslation(y => y.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
Id = item.Id,
- SeName = item.GetTranslation(y => y.SeName, _workContext.WorkingLanguage.Id),
+ SeName = item.GetTranslation(y => y.SeName, _workContextAccessor.WorkContext.WorkingLanguage.Id),
IsArticle = true,
FormattedBreadcrumbs =
(await _knowledgebaseService.GetPublicKnowledgebaseCategory(item.ParentCategoryId))
?.GetFormattedBreadCrumb(allCategories, ">") +
- " > " + item.GetTranslation(y => y.Name, _workContext.WorkingLanguage.Id)
+ " > " + item.GetTranslation(y => y.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id)
};
model.Items.Add(kbm);
}
@@ -177,7 +177,7 @@ public class KnowledgebaseController : BasePublicController
if (!_knowledgebaseSettings.Enabled)
return RedirectToRoute("HomePage");
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var article = await _knowledgebaseService.GetKnowledgebaseArticle(articleId);
if (article == null)
return RedirectToAction("List");
@@ -187,7 +187,7 @@ public class KnowledgebaseController : BasePublicController
return InvokeHttp404();
//Store acl
- if (!_aclService.Authorize(article, _workContext.CurrentStore.Id))
+ if (!_aclService.Authorize(article, _workContextAccessor.WorkContext.CurrentStore.Id))
return InvokeHttp404();
//display "edit" (manage) link
@@ -204,17 +204,17 @@ public class KnowledgebaseController : BasePublicController
private async Task PrepareKnowledgebaseArticleModel(KnowledgebaseArticleModel model, KnowledgebaseArticle article,
ICustomerService customerService)
{
- model.Content = article.GetTranslation(y => y.Content, _workContext.WorkingLanguage.Id);
- model.Name = article.GetTranslation(y => y.Name, _workContext.WorkingLanguage.Id);
+ model.Content = article.GetTranslation(y => y.Content, _workContextAccessor.WorkContext.WorkingLanguage.Id);
+ model.Name = article.GetTranslation(y => y.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id);
model.Id = article.Id;
model.ParentCategoryId = article.ParentCategoryId;
- model.SeName = article.GetTranslation(y => y.SeName, _workContext.WorkingLanguage.Id);
+ model.SeName = article.GetTranslation(y => y.SeName, _workContextAccessor.WorkContext.WorkingLanguage.Id);
model.AllowComments = article.AllowComments;
model.AddNewComment.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnArticleCommentPage;
- model.MetaTitle = article.GetTranslation(y => y.MetaTitle, _workContext.WorkingLanguage.Id);
- model.MetaDescription = article.GetTranslation(y => y.MetaDescription, _workContext.WorkingLanguage.Id);
- model.MetaKeywords = article.GetTranslation(y => y.MetaKeywords, _workContext.WorkingLanguage.Id);
+ model.MetaTitle = article.GetTranslation(y => y.MetaTitle, _workContextAccessor.WorkContext.WorkingLanguage.Id);
+ model.MetaDescription = article.GetTranslation(y => y.MetaDescription, _workContextAccessor.WorkContext.WorkingLanguage.Id);
+ model.MetaKeywords = article.GetTranslation(y => y.MetaKeywords, _workContextAccessor.WorkContext.WorkingLanguage.Id);
var articleComments = await _knowledgebaseService.GetArticleCommentsByArticleId(article.Id);
foreach (var ac in articleComments)
@@ -246,15 +246,15 @@ public class KnowledgebaseController : BasePublicController
{
var breadcrumbCacheKey = string.Format(CacheKeyConst.KNOWLEDGEBASE_CATEGORY_BREADCRUMB_KEY,
article.ParentCategoryId,
- string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),
- _workContext.CurrentStore.Id,
- _workContext.WorkingLanguage.Id);
+ string.Join(",", _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()),
+ _workContextAccessor.WorkContext.CurrentStore.Id,
+ _workContextAccessor.WorkContext.WorkingLanguage.Id);
model.CategoryBreadcrumb = await _cacheBase.GetAsync(breadcrumbCacheKey, async () =>
(await GetCategoryBreadCrumb(category))
.Select(catBr => new KnowledgebaseCategoryModel {
Id = catBr.Id,
- Name = catBr.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- SeName = catBr.GetSeName(_workContext.WorkingLanguage.Id)
+ Name = catBr.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ SeName = catBr.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id)
})
.ToList()
);
@@ -276,7 +276,7 @@ public class KnowledgebaseController : BasePublicController
if (ModelState.IsValid)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var comment = new KnowledgebaseArticleComment {
ArticleId = article.Id,
CustomerId = customer.Id,
@@ -297,7 +297,7 @@ public class KnowledgebaseController : BasePublicController
TempData["Grand.knowledgebase.addarticlecomment.result"] =
_translationService.GetResource("Knowledgebase.Article.Comments.SuccessfullyAdded");
return RedirectToRoute("KnowledgebaseArticle",
- new { SeName = article.GetSeName(_workContext.WorkingLanguage.Id) });
+ new { SeName = article.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id) });
}
//If we got this far, something failed, redisplay form
@@ -316,8 +316,8 @@ public class KnowledgebaseController : BasePublicController
while (category != null && //not null
(showHidden || category.Published) && //published
- (showHidden || _aclService.Authorize(category, _workContext.CurrentCustomer)) && //ACL
- (showHidden || _aclService.Authorize(category, _workContext.CurrentStore.Id)) && //Store acl
+ (showHidden || _aclService.Authorize(category, _workContextAccessor.WorkContext.CurrentCustomer)) && //ACL
+ (showHidden || _aclService.Authorize(category, _workContextAccessor.WorkContext.CurrentStore.Id)) && //Store acl
!alreadyProcessedCategoryIds.Contains(category.Id)) //prevent circular references
{
result.Add(category);
diff --git a/src/Web/Grand.Web/Controllers/MerchandiseReturnController.cs b/src/Web/Grand.Web/Controllers/MerchandiseReturnController.cs
index 50c5212eb..86b935726 100644
--- a/src/Web/Grand.Web/Controllers/MerchandiseReturnController.cs
+++ b/src/Web/Grand.Web/Controllers/MerchandiseReturnController.cs
@@ -27,7 +27,7 @@ public class MerchandiseReturnController : BasePublicController
public MerchandiseReturnController(
IMerchandiseReturnService merchandiseReturnService,
IOrderService orderService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
ITranslationService translationService,
IMediator mediator,
@@ -36,7 +36,7 @@ public class MerchandiseReturnController : BasePublicController
{
_merchandiseReturnService = merchandiseReturnService;
_orderService = orderService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_translationService = translationService;
_mediator = mediator;
@@ -50,7 +50,7 @@ public class MerchandiseReturnController : BasePublicController
private readonly IMerchandiseReturnService _merchandiseReturnService;
private readonly IOrderService _orderService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
private readonly ITranslationService _translationService;
private readonly IMediator _mediator;
@@ -65,11 +65,11 @@ public class MerchandiseReturnController : BasePublicController
{
var countryService = HttpContext.RequestServices.GetRequiredService<ICountryService>();
var countries =
- await countryService.GetAllCountries(_workContext.WorkingLanguage.Id, _workContext.CurrentStore.Id);
+ await countryService.GetAllCountries(_workContextAccessor.WorkContext.WorkingLanguage.Id, _workContextAccessor.WorkContext.CurrentStore.Id);
addressModel = await _mediator.Send(new GetAddressModel {
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
- Customer = _workContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
Model = addressModel,
Address = address,
ExcludeProperties = true,
@@ -85,13 +85,13 @@ public class MerchandiseReturnController : BasePublicController
if (!string.IsNullOrEmpty(model.PickupAddressId))
{
- address = _workContext.CurrentCustomer.Addresses.FirstOrDefault(a => a.Id == model.PickupAddressId);
+ address = _workContextAccessor.WorkContext.CurrentCustomer.Addresses.FirstOrDefault(a => a.Id == model.PickupAddressId);
}
else
{
var customAttributes = await _mediator.Send(new GetParseCustomAddressAttributes
{ SelectedAttributes = model.MerchandiseReturnNewAddress.SelectedAttributes });
- address = model.MerchandiseReturnNewAddress.ToEntity(_workContext.CurrentCustomer, _addressSettings);
+ address = model.MerchandiseReturnNewAddress.ToEntity(_workContextAccessor.WorkContext.CurrentCustomer, _addressSettings);
model.NewAddressPreselected = true;
address.Attributes = customAttributes;
}
@@ -106,13 +106,13 @@ public class MerchandiseReturnController : BasePublicController
[HttpGet]
public virtual async Task<IActionResult> CustomerMerchandiseReturns()
{
- if (!await _groupService.IsRegistered(_workContext.CurrentCustomer))
+ if (!await _groupService.IsRegistered(_workContextAccessor.WorkContext.CurrentCustomer))
return Challenge();
var model = await _mediator.Send(new GetMerchandiseReturns {
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore,
- Language = _workContext.WorkingLanguage
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage
});
return View(model);
@@ -122,7 +122,7 @@ public class MerchandiseReturnController : BasePublicController
public virtual async Task<IActionResult> MerchandiseReturn(string orderId)
{
var order = await _orderService.GetOrderById(orderId);
- if (!await order.Access(_workContext.CurrentCustomer, _groupService))
+ if (!await order.Access(_workContextAccessor.WorkContext.CurrentCustomer, _groupService))
return Challenge();
if (!await _mediator.Send(new IsMerchandiseReturnAllowedQuery { Order = order }))
@@ -130,8 +130,8 @@ public class MerchandiseReturnController : BasePublicController
var model = await _mediator.Send(new GetMerchandiseReturn {
Order = order,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return View(model);
}
@@ -141,7 +141,7 @@ public class MerchandiseReturnController : BasePublicController
public virtual async Task<IActionResult> MerchandiseReturn(MerchandiseReturnModel model)
{
var order = await _orderService.GetOrderById(model.OrderId);
- if (!await order.Access(_workContext.CurrentCustomer, _groupService))
+ if (!await order.Access(_workContextAccessor.WorkContext.CurrentCustomer, _groupService))
return Challenge();
if (!await _mediator.Send(new IsMerchandiseReturnAllowedQuery { Order = order }))
@@ -164,8 +164,8 @@ public class MerchandiseReturnController : BasePublicController
var returnModel = await _mediator.Send(new GetMerchandiseReturn {
Order = order,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
returnModel.Error = string.Join(", ",
ModelState.Keys.SelectMany(k => ModelState[k]!.Errors).Select(m => m.ErrorMessage).ToArray());
@@ -183,16 +183,16 @@ public class MerchandiseReturnController : BasePublicController
public virtual async Task<IActionResult> MerchandiseReturnDetails(string merchandiseReturnId)
{
var rr = await _merchandiseReturnService.GetMerchandiseReturnById(merchandiseReturnId);
- if (!await rr.Access(_workContext.CurrentCustomer, _groupService))
+ if (!await rr.Access(_workContextAccessor.WorkContext.CurrentCustomer, _groupService))
return Challenge();
var order = await _orderService.GetOrderById(rr.OrderId);
- if (!await order.Access(_workContext.CurrentCustomer, _groupService))
+ if (!await order.Access(_workContextAccessor.WorkContext.CurrentCustomer, _groupService))
return Challenge();
var model = await _mediator.Send(new GetMerchandiseReturnDetails {
Order = order,
- Language = _workContext.WorkingLanguage,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
MerchandiseReturn = rr
});
diff --git a/src/Web/Grand.Web/Controllers/NewsController.cs b/src/Web/Grand.Web/Controllers/NewsController.cs
index 1efad8a6e..379c117c9 100644
--- a/src/Web/Grand.Web/Controllers/NewsController.cs
+++ b/src/Web/Grand.Web/Controllers/NewsController.cs
@@ -24,7 +24,7 @@ public class NewsController : BasePublicController
#region Constructors
public NewsController(INewsService newsService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ITranslationService translationService,
IAclService aclService,
IPermissionService permissionService,
@@ -32,7 +32,7 @@ public class NewsController : BasePublicController
NewsSettings newsSettings)
{
_newsService = newsService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_translationService = translationService;
_aclService = aclService;
_permissionService = permissionService;
@@ -45,7 +45,7 @@ public class NewsController : BasePublicController
#region Fields
private readonly INewsService _newsService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ITranslationService _translationService;
private readonly IAclService _aclService;
private readonly IPermissionService _permissionService;
@@ -79,7 +79,7 @@ public class NewsController : BasePublicController
(newsItem.StartDateUtc.HasValue && newsItem.StartDateUtc.Value >= DateTime.UtcNow) ||
(newsItem.EndDateUtc.HasValue && newsItem.EndDateUtc.Value <= DateTime.UtcNow) ||
//Store acl
- !_aclService.Authorize(newsItem, _workContext.CurrentStore.Id))
+ !_aclService.Authorize(newsItem, _workContextAccessor.WorkContext.CurrentStore.Id))
return RedirectToRoute("HomePage");
var model = await _mediator.Send(new GetNewsItem { NewsItem = newsItem });
@@ -123,7 +123,7 @@ public class NewsController : BasePublicController
newsComment.CommentTitle,
CreatedOn = HttpContext.RequestServices.GetService<IDateTimeService>()
.ConvertToUserTime(newsComment.CreatedOnUtc, DateTimeKind.Utc),
- CustomerName = _workContext.CurrentCustomer.FormatUserName(HttpContext.RequestServices
+ CustomerName = _workContextAccessor.WorkContext.CurrentCustomer.FormatUserName(HttpContext.RequestServices
.GetService<CustomerSettings>().CustomerNameFormat)
}
});
diff --git a/src/Web/Grand.Web/Controllers/OrderController.cs b/src/Web/Grand.Web/Controllers/OrderController.cs
index f6257af3d..9389fb718 100644
--- a/src/Web/Grand.Web/Controllers/OrderController.cs
+++ b/src/Web/Grand.Web/Controllers/OrderController.cs
@@ -30,7 +30,7 @@ public class OrderController : BasePublicController
#region Constructors
public OrderController(IOrderService orderService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IPaymentService paymentService,
IPaymentTransactionService paymentTransactionService,
ITranslationService translationService,
@@ -39,7 +39,7 @@ public class OrderController : BasePublicController
OrderSettings orderSettings)
{
_orderService = orderService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_paymentService = paymentService;
_paymentTransactionService = paymentTransactionService;
_translationService = translationService;
@@ -53,7 +53,7 @@ public class OrderController : BasePublicController
#region Fields
private readonly IOrderService _orderService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IPaymentService _paymentService;
private readonly IPaymentTransactionService _paymentTransactionService;
private readonly ITranslationService _translationService;
@@ -71,9 +71,9 @@ public class OrderController : BasePublicController
public virtual async Task<IActionResult> CustomerOrders(OrderPagingModel command)
{
var model = await _mediator.Send(new GetCustomerOrderList {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Command = command
});
return View(model);
@@ -84,11 +84,11 @@ public class OrderController : BasePublicController
public virtual async Task<IActionResult> Details(string orderId)
{
var order = await _orderService.GetOrderById(orderId);
- if (!await order.Access(_workContext.CurrentCustomer, _groupService))
+ if (!await order.Access(_workContextAccessor.WorkContext.CurrentCustomer, _groupService))
return Challenge();
var model = await _mediator.Send(new GetOrderDetails
- { Order = order, Language = _workContext.WorkingLanguage });
+ { Order = order, Language = _workContextAccessor.WorkContext.WorkingLanguage });
return View(model);
}
@@ -98,7 +98,7 @@ public class OrderController : BasePublicController
public virtual async Task<IActionResult> CancelOrder(string orderId)
{
var order = await _orderService.GetOrderById(orderId);
- if (!await order.Access(_workContext.CurrentCustomer, _groupService)
+ if (!await order.Access(_workContextAccessor.WorkContext.CurrentCustomer, _groupService)
|| order.PaymentStatusId != PaymentStatus.Pending
|| (order.ShippingStatusId != ShippingStatus.ShippingNotRequired &&
order.ShippingStatusId != ShippingStatus.Pending)
@@ -117,14 +117,14 @@ public class OrderController : BasePublicController
public virtual async Task<IActionResult> GetPdfInvoice(string orderId, [FromServices] IPdfService pdfService)
{
var order = await _orderService.GetOrderById(orderId);
- if (!await order.Access(_workContext.CurrentCustomer, _groupService))
+ if (!await order.Access(_workContextAccessor.WorkContext.CurrentCustomer, _groupService))
return Challenge();
var orders = new List<Order> { order };
byte[] bytes;
using (var stream = new MemoryStream())
{
- await pdfService.PrintOrdersToPdf(stream, orders, _workContext.WorkingLanguage.Id);
+ await pdfService.PrintOrdersToPdf(stream, orders, _workContextAccessor.WorkContext.WorkingLanguage.Id);
bytes = stream.ToArray();
}
@@ -142,11 +142,11 @@ public class OrderController : BasePublicController
if (!ModelState.IsValid) return View("AddOrderNote", model);
var order = await _orderService.GetOrderById(model.OrderId);
- if (!await order.Access(_workContext.CurrentCustomer, _groupService))
+ if (!await order.Access(_workContextAccessor.WorkContext.CurrentCustomer, _groupService))
return Challenge();
await _mediator.Send(new InsertOrderNoteCommand
- { Order = order, OrderNote = model, Language = _workContext.WorkingLanguage });
+ { Order = order, OrderNote = model, Language = _workContextAccessor.WorkContext.WorkingLanguage });
//notification
await _mediator.Publish(new OrderNoteEvent(order, model));
@@ -160,7 +160,7 @@ public class OrderController : BasePublicController
public virtual async Task<IActionResult> ReOrder(string orderId)
{
var order = await _orderService.GetOrderById(orderId);
- if (!await order.Access(_workContext.CurrentCustomer, _groupService))
+ if (!await order.Access(_workContextAccessor.WorkContext.CurrentCustomer, _groupService))
return Challenge();
var warnings = await _mediator.Send(new ReOrderCommand { Order = order });
@@ -176,7 +176,7 @@ public class OrderController : BasePublicController
public virtual async Task<IActionResult> RePostPayment(string orderId)
{
var order = await _orderService.GetOrderById(orderId);
- if (!await order.Access(_workContext.CurrentCustomer, _groupService))
+ if (!await order.Access(_workContextAccessor.WorkContext.CurrentCustomer, _groupService))
return Challenge();
var paymentTransaction = await _paymentTransactionService.GetOrderByGuid(order.OrderGuid);
@@ -201,12 +201,12 @@ public class OrderController : BasePublicController
return Challenge();
var order = await _orderService.GetOrderById(shipment.OrderId);
- if (!await order.Access(_workContext.CurrentCustomer, _groupService))
+ if (!await order.Access(_workContextAccessor.WorkContext.CurrentCustomer, _groupService))
return Challenge();
var model = await _mediator.Send(new GetShipmentDetails {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
Order = order,
Shipment = shipment
});
@@ -224,9 +224,9 @@ public class OrderController : BasePublicController
return RedirectToRoute("CustomerInfo");
var model = await _mediator.Send(new GetCustomerLoyaltyPoints {
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore,
- Currency = _workContext.WorkingCurrency
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency
});
return View(model);
}
diff --git a/src/Web/Grand.Web/Controllers/OutOfStockSubscriptionController.cs b/src/Web/Grand.Web/Controllers/OutOfStockSubscriptionController.cs
index 8c1d38f5a..972c2ca79 100644
--- a/src/Web/Grand.Web/Controllers/OutOfStockSubscriptionController.cs
+++ b/src/Web/Grand.Web/Controllers/OutOfStockSubscriptionController.cs
@@ -21,7 +21,7 @@ public class OutOfStockSubscriptionController : BasePublicController
#region Constructors
public OutOfStockSubscriptionController(IProductService productService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IGroupService groupService,
ITranslationService translationService,
IOutOfStockSubscriptionService outOfStockSubscriptionService,
@@ -32,7 +32,7 @@ public class OutOfStockSubscriptionController : BasePublicController
ShoppingCartSettings shoppingCartSettings)
{
_productService = productService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_groupService = groupService;
_translationService = translationService;
_outOfStockSubscriptionService = outOfStockSubscriptionService;
@@ -48,7 +48,7 @@ public class OutOfStockSubscriptionController : BasePublicController
#region Fields
private readonly IProductService _productService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IGroupService _groupService;
private readonly ITranslationService _translationService;
private readonly IOutOfStockSubscriptionService _outOfStockSubscriptionService;
@@ -70,7 +70,7 @@ public class OutOfStockSubscriptionController : BasePublicController
if (product == null)
throw new ArgumentException("No product found with the specified id");
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
if (!await _groupService.IsRegistered(customer))
return Content(_translationService.GetResource("OutOfStockSubscriptions.OnlyRegistered"));
@@ -79,12 +79,12 @@ public class OutOfStockSubscriptionController : BasePublicController
warehouseId = _shoppingCartSettings.AllowToSelectWarehouse
? string.IsNullOrEmpty(warehouseId) ? "" : warehouseId
- : string.IsNullOrEmpty(_workContext.CurrentStore.DefaultWarehouseId)
+ : string.IsNullOrEmpty(_workContextAccessor.WorkContext.CurrentStore.DefaultWarehouseId)
? product.WarehouseId
- : _workContext.CurrentStore.DefaultWarehouseId;
+ : _workContextAccessor.WorkContext.CurrentStore.DefaultWarehouseId;
var subscription = await _outOfStockSubscriptionService
- .FindSubscription(customer.Id, product.Id, null, _workContext.CurrentStore.Id,
+ .FindSubscription(customer.Id, product.Id, null, _workContextAccessor.WorkContext.CurrentStore.Id,
warehouseId);
return Content(subscription != null
@@ -99,11 +99,11 @@ public class OutOfStockSubscriptionController : BasePublicController
if (product == null)
throw new ArgumentException("No product found with the specified id");
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var warehouseId = _shoppingCartSettings.AllowToSelectWarehouse ? model.WarehouseId :
- product.UseMultipleWarehouses ? _workContext.CurrentStore.DefaultWarehouseId :
- string.IsNullOrEmpty(_workContext.CurrentStore.DefaultWarehouseId) ? product.WarehouseId :
- _workContext.CurrentStore.DefaultWarehouseId;
+ product.UseMultipleWarehouses ? _workContextAccessor.WorkContext.CurrentStore.DefaultWarehouseId :
+ string.IsNullOrEmpty(_workContextAccessor.WorkContext.CurrentStore.DefaultWarehouseId) ? product.WarehouseId :
+ _workContextAccessor.WorkContext.CurrentStore.DefaultWarehouseId;
if (!await _groupService.IsRegistered(customer))
return Json(new {
@@ -118,7 +118,7 @@ public class OutOfStockSubscriptionController : BasePublicController
_stockQuantityService.GetTotalStockQuantity(product, warehouseId: warehouseId) <= 0)
{
var subscription = await _outOfStockSubscriptionService
- .FindSubscription(customer.Id, product.Id, null, _workContext.CurrentStore.Id, warehouseId);
+ .FindSubscription(customer.Id, product.Id, null, _workContextAccessor.WorkContext.CurrentStore.Id, warehouseId);
if (subscription != null)
{
//subscription already exists
@@ -136,7 +136,7 @@ public class OutOfStockSubscriptionController : BasePublicController
subscription = new OutOfStockSubscription {
CustomerId = customer.Id,
ProductId = product.Id,
- StoreId = _workContext.CurrentStore.Id,
+ StoreId = _workContextAccessor.WorkContext.CurrentStore.Id,
WarehouseId = warehouseId
};
await _outOfStockSubscriptionService.InsertSubscription(subscription);
@@ -159,7 +159,7 @@ public class OutOfStockSubscriptionController : BasePublicController
var attributes = await _mediator.Send(new GetParseProductAttributes
{ Product = product, Attributes = model.Attributes });
var subscriptionAttributes = await _outOfStockSubscriptionService
- .FindSubscription(customer.Id, product.Id, attributes, _workContext.CurrentStore.Id, warehouseId);
+ .FindSubscription(customer.Id, product.Id, attributes, _workContextAccessor.WorkContext.CurrentStore.Id, warehouseId);
if (subscriptionAttributes != null)
{
@@ -180,7 +180,7 @@ public class OutOfStockSubscriptionController : BasePublicController
AttributeInfo = !attributes.Any()
? ""
: await _productAttributeFormatter.FormatAttributes(product, attributes),
- StoreId = _workContext.CurrentStore.Id,
+ StoreId = _workContextAccessor.WorkContext.CurrentStore.Id,
WarehouseId = warehouseId
};
@@ -204,9 +204,9 @@ public class OutOfStockSubscriptionController : BasePublicController
const int pageSize = 10;
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var list = await _outOfStockSubscriptionService.GetAllSubscriptionsByCustomerId(customer.Id,
- _workContext.CurrentStore.Id, pageIndex, pageSize);
+ _workContextAccessor.WorkContext.CurrentStore.Id, pageIndex, pageSize);
var model = new CustomerOutOfStockSubscriptionsModel();
@@ -217,11 +217,11 @@ public class OutOfStockSubscriptionController : BasePublicController
var subscriptionModel = new CustomerOutOfStockSubscriptionsModel.OutOfStockSubscriptionModel {
Id = subscription.Id,
ProductId = product.Id,
- ProductName = product.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
+ ProductName = product.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
AttributeDescription = !subscription.Attributes.Any()
? ""
: await _productAttributeFormatter.FormatAttributes(product, subscription.Attributes),
- SeName = product.GetSeName(_workContext.WorkingLanguage.Id)
+ SeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id)
};
model.Subscriptions.Add(subscriptionModel);
}
@@ -237,7 +237,7 @@ public class OutOfStockSubscriptionController : BasePublicController
foreach (var id in subscriptions)
{
var subscription = await _outOfStockSubscriptionService.GetSubscriptionById(id);
- if (subscription != null && subscription.CustomerId == _workContext.CurrentCustomer.Id)
+ if (subscription != null && subscription.CustomerId == _workContextAccessor.WorkContext.CurrentCustomer.Id)
await _outOfStockSubscriptionService.DeleteSubscription(subscription);
}
diff --git a/src/Web/Grand.Web/Controllers/ProductController.cs b/src/Web/Grand.Web/Controllers/ProductController.cs
index 1d3d16867..5f8b98337 100644
--- a/src/Web/Grand.Web/Controllers/ProductController.cs
+++ b/src/Web/Grand.Web/Controllers/ProductController.cs
@@ -32,7 +32,7 @@ public class ProductController : BasePublicController
public ProductController(
IProductService productService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ITranslationService translationService,
IRecentlyViewedProductsService recentlyViewedProductsService,
IShoppingCartService shoppingCartService,
@@ -44,7 +44,7 @@ public class ProductController : BasePublicController
)
{
_productService = productService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_translationService = translationService;
_recentlyViewedProductsService = recentlyViewedProductsService;
_shoppingCartService = shoppingCartService;
@@ -65,7 +65,7 @@ public class ProductController : BasePublicController
if (!_catalogSettings.RecentlyViewedProductsEnabled)
return Content("");
- var products = await _recentlyViewedProductsService.GetRecentlyViewedProducts(_workContext.CurrentCustomer.Id,
+ var products = await _recentlyViewedProductsService.GetRecentlyViewedProducts(_workContextAccessor.WorkContext.CurrentCustomer.Id,
_catalogSettings.RecentlyViewedProductsNumber);
//prepare model
@@ -112,7 +112,7 @@ public class ProductController : BasePublicController
return Content("");
var products = (await _productService.SearchProducts(
- storeId: _workContext.CurrentStore.Id,
+ storeId: _workContextAccessor.WorkContext.CurrentStore.Id,
visibleIndividuallyOnly: true,
markedAsNewOnly: true,
orderBy: ProductSortingEnum.CreatedOn,
@@ -144,16 +144,16 @@ public class ProductController : BasePublicController
if (ModelState.IsValid)
{
await _mediator.Send(new SendProductEmailAFriendMessageCommand {
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
Product = product,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Model = model
});
model.ProductId = product.Id;
- model.ProductName = product.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id);
- model.ProductSeName = product.GetSeName(_workContext.WorkingLanguage.Id);
+ model.ProductName = product.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id);
+ model.ProductSeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id);
model.SuccessfullySent = true;
model.Result = _translationService.GetResource("Products.EmailAFriend.SuccessfullySent");
@@ -163,8 +163,8 @@ public class ProductController : BasePublicController
//If we got this far, something failed, redisplay form
model.ProductId = product.Id;
- model.ProductName = product.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id);
- model.ProductSeName = product.GetSeName(_workContext.WorkingLanguage.Id);
+ model.ProductName = product.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id);
+ model.ProductSeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id);
model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnEmailProductToFriendPage;
model.SuccessfullySent = false;
model.Result = string.Join(",", ModelState.Values.SelectMany(v => v.Errors).Select(x => x.ErrorMessage));
@@ -204,9 +204,9 @@ public class ProductController : BasePublicController
// email
await _mediator.Send(new SendProductAskQuestionMessageCommand {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Model = productaskqestionmodel,
Product = product,
RemoteIpAddress = HttpContext.Connection?.RemoteIpAddress?.ToString()
@@ -233,7 +233,7 @@ public class ProductController : BasePublicController
if (!string.IsNullOrEmpty(parameter)) query = query.Where(x => x.Parameter == parameter);
var reservations = query.ToList();
- var inCart = (await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id))
+ var inCart = (await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id))
.Where(x => !string.IsNullOrEmpty(x.ReservationId)).ToList();
foreach (var cartItem in inCart)
{
@@ -251,7 +251,7 @@ public class ProductController : BasePublicController
#region Fields
private readonly IProductService _productService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ITranslationService _translationService;
private readonly IRecentlyViewedProductsService _recentlyViewedProductsService;
private readonly IShoppingCartService _shoppingCartService;
@@ -272,7 +272,7 @@ public class ProductController : BasePublicController
if (product == null)
return InvokeHttp404();
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
//published?
if (!_catalogSettings.AllowViewUnpublishedProductPage)
@@ -286,7 +286,7 @@ public class ProductController : BasePublicController
return InvokeHttp404();
//Store access
- if (!_aclService.Authorize(product, _workContext.CurrentStore.Id))
+ if (!_aclService.Authorize(product, _workContextAccessor.WorkContext.CurrentStore.Id))
return InvokeHttp404();
//availability dates
@@ -301,12 +301,12 @@ public class ProductController : BasePublicController
return parentGroupedProduct == null
? RedirectToRoute("HomePage")
: RedirectToRoute("Product",
- new { SeName = parentGroupedProduct.GetSeName(_workContext.WorkingLanguage.Id) });
+ new { SeName = parentGroupedProduct.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id) });
}
//prepare the model
var model = await _mediator.Send(new GetProductDetailsPage {
- Store = _workContext.CurrentStore,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Product = product,
IsAssociatedProduct = false
});
@@ -322,7 +322,7 @@ public class ProductController : BasePublicController
if (await _permissionService.Authorize(StandardPermission.ManageAccessAdminPanel, customer) &&
await _permissionService.Authorize(StandardPermission.ManageProducts, customer))
//a vendor should have access only to his products
- if (_workContext.CurrentVendor == null || _workContext.CurrentVendor.Id == product.VendorId)
+ if (_workContextAccessor.WorkContext.CurrentVendor == null || _workContextAccessor.WorkContext.CurrentVendor.Id == product.VendorId)
DisplayEditLink(Url.Action("Edit", "Product", new { id = product.Id, area = "Admin" }));
_ = _productService.IncrementProductField(product, x => x.Viewed, 1);
@@ -339,9 +339,9 @@ public class ProductController : BasePublicController
return new JsonResult("");
var modelProduct = await _mediator.Send(new GetProductDetailsAttributeChange {
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Model = model,
Product = product
});
@@ -440,7 +440,7 @@ public class ProductController : BasePublicController
var download = new Download {
DownloadGuid = Guid.NewGuid(),
- CustomerId = _workContext.CurrentCustomer.Id,
+ CustomerId = _workContextAccessor.WorkContext.CurrentCustomer.Id,
UseDownloadUrl = false,
DownloadUrl = "",
DownloadBinary = fileBinary,
@@ -474,7 +474,7 @@ public class ProductController : BasePublicController
message = "No product found with the specified ID"
});
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
//published?
if (!_catalogSettings.AllowViewUnpublishedProductPage)
@@ -494,7 +494,7 @@ public class ProductController : BasePublicController
});
//Store access
- if (!_aclService.Authorize(product, _workContext.CurrentStore.Id))
+ if (!_aclService.Authorize(product, _workContextAccessor.WorkContext.CurrentStore.Id))
return Json(new {
success = false,
message = "No product found with the specified ID"
@@ -517,13 +517,13 @@ public class ProductController : BasePublicController
redirect = Url.RouteUrl("HomePage")
});
return Json(new {
- redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContext.WorkingLanguage.Id) })
+ redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id) })
});
}
//prepare the model
var model = await _mediator.Send(new GetProductDetailsPage {
- Store = _workContext.CurrentStore,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Product = product,
IsAssociatedProduct = false,
UpdateCartItem = null
@@ -565,8 +565,8 @@ public class ProductController : BasePublicController
if (ModelState.IsValid)
{
var productReview = await _mediator.Send(new InsertProductReviewCommand {
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Model = model,
Product = product
});
@@ -579,10 +579,10 @@ public class ProductController : BasePublicController
await _mediator.Publish(new ProductReviewApprovedEvent(productReview));
model = await _mediator.Send(new GetProductReviews {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
Product = product,
- Store = _workContext.CurrentStore,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Size = _catalogSettings.NumberOfReview
});
@@ -599,8 +599,8 @@ public class ProductController : BasePublicController
model.AddProductReview.Result = _translationService.GetResource("Reviews.SuccessfullyAdded");
model.ProductReviewOverviewModel = await _mediator.Send(new GetProductReviewOverview {
Product = product,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
}
@@ -609,10 +609,10 @@ public class ProductController : BasePublicController
//If we got this far, something failed, redisplay form
var newmodel = await _mediator.Send(new GetProductReviews {
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
Product = product,
- Store = _workContext.CurrentStore,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Size = _catalogSettings.NumberOfReview
});
@@ -637,7 +637,7 @@ public class ProductController : BasePublicController
if (productReview == null)
throw new ArgumentException("No product review found with the specified id");
- if (await groupService.IsGuest(_workContext.CurrentCustomer) &&
+ if (await groupService.IsGuest(_workContextAccessor.WorkContext.CurrentCustomer) &&
!_catalogSettings.AllowAnonymousUsersToReviewProduct)
return Json(new {
Result = _translationService.GetResource("Reviews.Helpfulness.OnlyRegistered"),
@@ -646,7 +646,7 @@ public class ProductController : BasePublicController
});
//customers aren't allowed to vote for their own reviews
- if (productReview.CustomerId == _workContext.CurrentCustomer.Id)
+ if (productReview.CustomerId == _workContextAccessor.WorkContext.CurrentCustomer.Id)
return Json(new {
Result = _translationService.GetResource("Reviews.Helpfulness.YourOwnReview"),
TotalYes = productReview.HelpfulYesTotal,
@@ -655,7 +655,7 @@ public class ProductController : BasePublicController
//delete previous helpfulness
var prh = productReview.ProductReviewHelpfulnessEntries
- .FirstOrDefault(x => x.CustomerId == _workContext.CurrentCustomer.Id);
+ .FirstOrDefault(x => x.CustomerId == _workContextAccessor.WorkContext.CurrentCustomer.Id);
if (prh != null)
{
//existing one
@@ -666,13 +666,13 @@ public class ProductController : BasePublicController
//insert new helpfulness
prh = new ProductReviewHelpfulness {
ProductReviewId = productReview.Id,
- CustomerId = _workContext.CurrentCustomer.Id,
+ CustomerId = _workContextAccessor.WorkContext.CurrentCustomer.Id,
WasHelpful = washelpful
};
productReview.ProductReviewHelpfulnessEntries.Add(prh);
await productReviewService.UpdateProductReview(productReview);
- if (!_workContext.CurrentCustomer.HasContributions)
- await customerService.UpdateContributions(_workContext.CurrentCustomer);
+ if (!_workContextAccessor.WorkContext.CurrentCustomer.HasContributions)
+ await customerService.UpdateContributions(_workContextAccessor.WorkContext.CurrentCustomer);
}
//new totals
diff --git a/src/Web/Grand.Web/Controllers/PushNotificationsController.cs b/src/Web/Grand.Web/Controllers/PushNotificationsController.cs
index 0c2941f18..08eee95c6 100644
--- a/src/Web/Grand.Web/Controllers/PushNotificationsController.cs
+++ b/src/Web/Grand.Web/Controllers/PushNotificationsController.cs
@@ -10,11 +10,11 @@ namespace Grand.Web.Controllers;
public class PushNotificationsController : BasePublicController
{
private readonly IPushNotificationsService _pushNotificationsService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public PushNotificationsController(IWorkContext workContext, IPushNotificationsService pushNotificationsService)
+ public PushNotificationsController(IWorkContextAccessor workContextAccessor, IPushNotificationsService pushNotificationsService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_pushNotificationsService = pushNotificationsService;
}
@@ -24,12 +24,12 @@ public class PushNotificationsController : BasePublicController
{
if (success)
{
- var toUpdate = await _pushNotificationsService.GetPushReceiverByCustomerId(_workContext.CurrentCustomer.Id);
+ var toUpdate = await _pushNotificationsService.GetPushReceiverByCustomerId(_workContextAccessor.WorkContext.CurrentCustomer.Id);
if (toUpdate == null)
{
await _pushNotificationsService.InsertPushReceiver(new PushRegistration {
- CustomerId = _workContext.CurrentCustomer.Id,
+ CustomerId = _workContextAccessor.WorkContext.CurrentCustomer.Id,
Token = value,
RegisteredOn = DateTime.UtcNow,
Allowed = true
@@ -46,12 +46,12 @@ public class PushNotificationsController : BasePublicController
else
{
if (value != "Permission denied") return new JsonResult("");
- var toUpdate = await _pushNotificationsService.GetPushReceiverByCustomerId(_workContext.CurrentCustomer.Id);
+ var toUpdate = await _pushNotificationsService.GetPushReceiverByCustomerId(_workContextAccessor.WorkContext.CurrentCustomer.Id);
if (toUpdate == null)
{
await _pushNotificationsService.InsertPushReceiver(new PushRegistration {
- CustomerId = _workContext.CurrentCustomer.Id,
+ CustomerId = _workContextAccessor.WorkContext.CurrentCustomer.Id,
Token = "[DENIED]",
RegisteredOn = DateTime.UtcNow,
Allowed = false
diff --git a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs b/src/Web/Grand.Web/Controllers/ShoppingCartController.cs
index 133a174de..5a0578576 100644
--- a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs
+++ b/src/Web/Grand.Web/Controllers/ShoppingCartController.cs
@@ -32,7 +32,7 @@ public class ShoppingCartController : BasePublicController
#region Constructors
public ShoppingCartController(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IShoppingCartService shoppingCartService,
ITranslationService translationService,
IDiscountService discountService,
@@ -45,7 +45,7 @@ public class ShoppingCartController : BasePublicController
ShoppingCartSettings shoppingCartSettings,
OrderSettings orderSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_shoppingCartService = shoppingCartService;
_translationService = translationService;
_discountService = discountService;
@@ -79,7 +79,7 @@ public class ShoppingCartController : BasePublicController
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IShoppingCartService _shoppingCartService;
private readonly ITranslationService _translationService;
private readonly IDiscountService _discountService;
@@ -107,11 +107,11 @@ public class ShoppingCartController : BasePublicController
return Content("");
var model = await _mediator.Send(new GetMiniShoppingCart {
- Customer = _workContext.CurrentCustomer,
- Currency = _workContext.WorkingCurrency,
- Language = _workContext.WorkingLanguage,
- TaxDisplayType = _workContext.TaxDisplayType,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return Json(model);
}
@@ -122,12 +122,12 @@ public class ShoppingCartController : BasePublicController
[FromServices] ICheckoutAttributeParser checkoutAttributeParser,
[FromServices] ICheckoutAttributeFormatter checkoutAttributeFormatter)
{
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.ShoppingCart, ShoppingCartType.Auctions);
var checkoutAttributes = await _mediator.Send(new SaveCheckoutAttributesCommand {
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Cart = cart,
SelectedAttributes = model.Attributes
});
@@ -135,7 +135,7 @@ public class ShoppingCartController : BasePublicController
var enabledAttributeIds = new List<string>();
var disabledAttributeIds = new List<string>();
var attributes =
- await _checkoutAttributeService.GetAllCheckoutAttributes(_workContext.CurrentStore.Id,
+ await _checkoutAttributeService.GetAllCheckoutAttributes(_workContextAccessor.WorkContext.CurrentStore.Id,
!cart.RequiresShipping());
foreach (var attribute in attributes)
{
@@ -151,11 +151,11 @@ public class ShoppingCartController : BasePublicController
var orderTotals = await _mediator.Send(new GetOrderTotals {
Cart = cart,
IsEditable = true,
- Store = _workContext.CurrentStore,
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- TaxDisplayType = _workContext.TaxDisplayType
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType
});
return Json(new {
@@ -163,7 +163,7 @@ public class ShoppingCartController : BasePublicController
disabledattributeids = disabledAttributeIds.ToArray(),
model = orderTotals,
checkoutattributeinfo =
- await checkoutAttributeFormatter.FormatAttributes(checkoutAttributes, _workContext.CurrentCustomer)
+ await checkoutAttributeFormatter.FormatAttributes(checkoutAttributes, _workContextAccessor.WorkContext.CurrentCustomer)
});
}
@@ -229,7 +229,7 @@ public class ShoppingCartController : BasePublicController
var download = new Download {
DownloadGuid = Guid.NewGuid(),
- CustomerId = _workContext.CurrentCustomer.Id,
+ CustomerId = _workContextAccessor.WorkContext.CurrentCustomer.Id,
UseDownloadUrl = false,
DownloadUrl = "",
DownloadBinary = fileBinary,
@@ -258,15 +258,15 @@ public class ShoppingCartController : BasePublicController
if (!await _permissionService.Authorize(StandardPermission.EnableShoppingCart))
return RedirectToRoute("HomePage");
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, PrepareCartTypes());
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id, PrepareCartTypes());
var model = await _mediator.Send(new GetShoppingCart {
Cart = cart,
ValidateCheckoutAttributes = checkoutAttributes,
- Customer = _workContext.CurrentCustomer,
- Currency = _workContext.WorkingCurrency,
- Language = _workContext.WorkingLanguage,
- TaxDisplayType = _workContext.TaxDisplayType,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return View(model);
}
@@ -276,17 +276,17 @@ public class ShoppingCartController : BasePublicController
[ProducesResponseType(typeof(ShoppingCartModel), StatusCodes.Status200OK)]
public async Task<IActionResult> CartSummary()
{
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.ShoppingCart, ShoppingCartType.Auctions);
var model = await _mediator.Send(new GetShoppingCart {
Cart = cart,
IsEditable = false,
- Customer = _workContext.CurrentCustomer,
- Currency = _workContext.WorkingCurrency,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
- TaxDisplayType = _workContext.TaxDisplayType
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType
});
return Json(model);
@@ -297,16 +297,16 @@ public class ShoppingCartController : BasePublicController
[ProducesResponseType(typeof(OrderTotalsModel), StatusCodes.Status200OK)]
public async Task<IActionResult> CartTotal()
{
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.ShoppingCart, ShoppingCartType.Auctions);
var model = await _mediator.Send(new GetOrderTotals {
Cart = cart,
- Store = _workContext.CurrentStore,
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- TaxDisplayType = _workContext.TaxDisplayType
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType
});
return Json(model);
}
@@ -323,13 +323,13 @@ public class ShoppingCartController : BasePublicController
warnings = string.Join(',', ModelState.Values.SelectMany(x => x.Errors.Select(x => x.ErrorMessage)))
});
- var cart = (await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, PrepareCartTypes()))
+ var cart = (await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id, PrepareCartTypes()))
.FirstOrDefault(x => x.Id == model.ShoppingCartId);
var warnings = new List<string>();
if (cart != null)
{
- var currSciWarnings = await _shoppingCartService.UpdateShoppingCartItem(_workContext.CurrentCustomer,
+ var currSciWarnings = await _shoppingCartService.UpdateShoppingCartItem(_workContextAccessor.WorkContext.CurrentCustomer,
cart.Id, cart.WarehouseId, cart.Attributes, cart.EnteredPrice,
cart.RentalStartDateUtc, cart.RentalEndDateUtc,
model.Quantity);
@@ -337,12 +337,12 @@ public class ShoppingCartController : BasePublicController
}
var cartModel = await _mediator.Send(new GetShoppingCart {
- Cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, PrepareCartTypes()),
- Customer = _workContext.CurrentCustomer,
- Currency = _workContext.WorkingCurrency,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
- TaxDisplayType = _workContext.TaxDisplayType
+ Cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id, PrepareCartTypes()),
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType
});
return Json(new {
@@ -361,10 +361,10 @@ public class ShoppingCartController : BasePublicController
if (!await _permissionService.Authorize(StandardPermission.EnableShoppingCart))
return RedirectToRoute("HomePage");
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, PrepareCartTypes());
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id, PrepareCartTypes());
foreach (var sci in cart)
- await _shoppingCartService.DeleteShoppingCartItem(_workContext.CurrentCustomer, sci,
+ await _shoppingCartService.DeleteShoppingCartItem(_workContextAccessor.WorkContext.CurrentCustomer, sci,
ensureOnlyActiveCheckoutAttributes: true);
return RedirectToRoute("HomePage");
@@ -381,20 +381,20 @@ public class ShoppingCartController : BasePublicController
if (_shoppingCartSettings.AllowOnHoldCart)
shoppingCartTypes.Add(ShoppingCartType.OnHoldCart);
- var item = (await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var item = (await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
shoppingCartTypes.ToArray()))
.FirstOrDefault(sci => sci.Id == model.Id);
if (item != null)
- await _shoppingCartService.DeleteShoppingCartItem(_workContext.CurrentCustomer, item,
+ await _shoppingCartService.DeleteShoppingCartItem(_workContextAccessor.WorkContext.CurrentCustomer, item,
ensureOnlyActiveCheckoutAttributes: true);
var miniShoppingCartmodel = await _mediator.Send(new GetMiniShoppingCart {
- Customer = _workContext.CurrentCustomer,
- Currency = _workContext.WorkingCurrency,
- Language = _workContext.WorkingLanguage,
- TaxDisplayType = _workContext.TaxDisplayType,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
if (!model.ShoppingCartPage)
return Json(new {
@@ -403,14 +403,14 @@ public class ShoppingCartController : BasePublicController
sidebarshoppingcartmodel = miniShoppingCartmodel
});
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, PrepareCartTypes());
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id, PrepareCartTypes());
var shoppingcartmodel = await _mediator.Send(new GetShoppingCart {
Cart = cart,
- Customer = _workContext.CurrentCustomer,
- Currency = _workContext.WorkingCurrency,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
- TaxDisplayType = _workContext.TaxDisplayType
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType
});
return Json(new {
@@ -435,32 +435,32 @@ public class ShoppingCartController : BasePublicController
if (_shoppingCartSettings.AllowOnHoldCart)
shoppingCartTypes.Add(ShoppingCartType.OnHoldCart);
- var item = (await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var item = (await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
shoppingCartTypes.ToArray()))
.FirstOrDefault(sci => sci.Id == model.Id);
if (item != null)
{
item.ShoppingCartTypeId = model.Status ? ShoppingCartType.ShoppingCart : ShoppingCartType.OnHoldCart;
- await _customerService.UpdateShoppingCartItem(_workContext.CurrentCustomer.Id, item);
+ await _customerService.UpdateShoppingCartItem(_workContextAccessor.WorkContext.CurrentCustomer.Id, item);
}
var miniShoppingCart = await _mediator.Send(new GetMiniShoppingCart {
- Customer = _workContext.CurrentCustomer,
- Currency = _workContext.WorkingCurrency,
- Language = _workContext.WorkingLanguage,
- TaxDisplayType = _workContext.TaxDisplayType,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, PrepareCartTypes());
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id, PrepareCartTypes());
var shoppingcartmodel = await _mediator.Send(new GetShoppingCart {
Cart = cart,
- Customer = _workContext.CurrentCustomer,
- Currency = _workContext.WorkingCurrency,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
- TaxDisplayType = _workContext.TaxDisplayType
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType
});
return Json(new {
@@ -480,28 +480,28 @@ public class ShoppingCartController : BasePublicController
[DenySystemAccount]
public virtual async Task<IActionResult> StartCheckout(CheckoutAttributeSelectedModel model)
{
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.ShoppingCart, ShoppingCartType.Auctions);
List<CustomAttribute> checkoutAttributes;
//parse and save checkout attributes
if (model?.Attributes is { Count: > 0 })
checkoutAttributes = (await _mediator.Send(new SaveCheckoutAttributesCommand {
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
Cart = cart,
SelectedAttributes = model.Attributes
})).ToList();
else
checkoutAttributes =
- _workContext.CurrentCustomer.GetUserFieldFromEntity<List<CustomAttribute>>(
- SystemCustomerFieldNames.CheckoutAttributes, _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<List<CustomAttribute>>(
+ SystemCustomerFieldNames.CheckoutAttributes, _workContextAccessor.WorkContext.CurrentStore.Id);
var checkoutAttributeWarnings =
await _shoppingCartValidator.GetShoppingCartWarnings(cart, checkoutAttributes, true, true);
if (checkoutAttributeWarnings.Any()) return RedirectToRoute("ShoppingCart", new { checkoutAttributes = true });
//everything is OK
- if (!await _groupService.IsGuest(_workContext.CurrentCustomer)) return RedirectToRoute("Checkout");
+ if (!await _groupService.IsGuest(_workContextAccessor.WorkContext.CurrentCustomer)) return RedirectToRoute("Checkout");
if (!_orderSettings.AnonymousCheckoutAllowed)
return Challenge();
@@ -513,7 +513,7 @@ public class ShoppingCartController : BasePublicController
[HttpPost]
public virtual async Task<IActionResult> ApplyDiscountCoupon(DiscountCouponModel model)
{
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, PrepareCartTypes());
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id, PrepareCartTypes());
var message = string.Empty;
var isApplied = false;
@@ -522,10 +522,10 @@ public class ShoppingCartController : BasePublicController
{
//valid
var applyCouponCode =
- _workContext.CurrentCustomer.ApplyCouponCode(SystemCustomerFieldNames.DiscountCoupons,
+ _workContextAccessor.WorkContext.CurrentCustomer.ApplyCouponCode(SystemCustomerFieldNames.DiscountCoupons,
model.DiscountCouponCode);
//apply new value
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.DiscountCoupons, applyCouponCode);
message = _translationService.GetResource("ShoppingCart.DiscountCouponCode.Applied");
isApplied = true;
@@ -537,11 +537,11 @@ public class ShoppingCartController : BasePublicController
var cartModel = await _mediator.Send(new GetShoppingCart {
Cart = cart,
- Customer = _workContext.CurrentCustomer,
- Currency = _workContext.WorkingCurrency,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
- TaxDisplayType = _workContext.TaxDisplayType
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType
});
cartModel.DiscountBox.Message = message;
@@ -557,7 +557,7 @@ public class ShoppingCartController : BasePublicController
[HttpPost]
public virtual async Task<IActionResult> ApplyGiftVoucher(GiftVoucherCouponModel model)
{
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, PrepareCartTypes());
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id, PrepareCartTypes());
var message = string.Empty;
var isApplied = false;
@@ -566,10 +566,10 @@ public class ShoppingCartController : BasePublicController
{
model.GiftVoucherCouponCode = model.GiftVoucherCouponCode.Trim();
- var result = _workContext.CurrentCustomer.ApplyCouponCode(SystemCustomerFieldNames.GiftVoucherCoupons,
+ var result = _workContextAccessor.WorkContext.CurrentCustomer.ApplyCouponCode(SystemCustomerFieldNames.GiftVoucherCoupons,
model.GiftVoucherCouponCode.ToLower());
//apply new value
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.GiftVoucherCoupons, result);
message = _translationService.GetResource("ShoppingCart.Code.Applied");
@@ -582,11 +582,11 @@ public class ShoppingCartController : BasePublicController
var cartModel = await _mediator.Send(new GetShoppingCart {
Cart = cart,
- Customer = _workContext.CurrentCustomer,
- Currency = _workContext.WorkingCurrency,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
- TaxDisplayType = _workContext.TaxDisplayType
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType
});
cartModel.GiftVoucherBox.Message = message;
@@ -601,14 +601,14 @@ public class ShoppingCartController : BasePublicController
[HttpPost]
public virtual async Task<IActionResult> GetEstimateShipping(EstimateShippingModel model)
{
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id,
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id,
ShoppingCartType.ShoppingCart, ShoppingCartType.Auctions);
var result = await _mediator.Send(new GetEstimateShippingResult {
Cart = cart,
- Currency = _workContext.WorkingCurrency,
- Customer = _workContext.CurrentCustomer,
- Store = _workContext.CurrentStore,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
CountryId = model.CountryId,
StateProvinceId = model.StateProvinceId,
ZipPostalCode = model.ZipPostalCode
@@ -625,7 +625,7 @@ public class ShoppingCartController : BasePublicController
if (discount != null)
{
var coupons =
- _workContext.CurrentCustomer.ParseAppliedCouponCodes(SystemCustomerFieldNames.DiscountCoupons);
+ _workContextAccessor.WorkContext.CurrentCustomer.ParseAppliedCouponCodes(SystemCustomerFieldNames.DiscountCoupons);
foreach (var item in coupons)
{
var dd = await _discountService.GetDiscountByCouponCode(item);
@@ -633,21 +633,21 @@ public class ShoppingCartController : BasePublicController
//remove coupon
var result =
- _workContext.CurrentCustomer.RemoveCouponCode(SystemCustomerFieldNames.DiscountCoupons, item);
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.CurrentCustomer.RemoveCouponCode(SystemCustomerFieldNames.DiscountCoupons, item);
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.DiscountCoupons, result);
}
}
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, PrepareCartTypes());
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id, PrepareCartTypes());
var model = await _mediator.Send(new GetShoppingCart {
Cart = cart,
- Customer = _workContext.CurrentCustomer,
- Currency = _workContext.WorkingCurrency,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
- TaxDisplayType = _workContext.TaxDisplayType
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType
});
return Json(new {
@@ -667,22 +667,22 @@ public class ShoppingCartController : BasePublicController
if (giftvoucher != null)
{
var result =
- _workContext.CurrentCustomer.RemoveCouponCode(SystemCustomerFieldNames.GiftVoucherCoupons,
+ _workContextAccessor.WorkContext.CurrentCustomer.RemoveCouponCode(SystemCustomerFieldNames.GiftVoucherCoupons,
giftvoucher.Code);
- await _customerService.UpdateUserField(_workContext.CurrentCustomer,
+ await _customerService.UpdateUserField(_workContextAccessor.WorkContext.CurrentCustomer,
SystemCustomerFieldNames.GiftVoucherCoupons, result);
}
}
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, PrepareCartTypes());
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id, PrepareCartTypes());
var model = await _mediator.Send(new GetShoppingCart {
Cart = cart,
- Customer = _workContext.CurrentCustomer,
- Currency = _workContext.WorkingCurrency,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore,
- TaxDisplayType = _workContext.TaxDisplayType
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType
});
return Json(new {
diff --git a/src/Web/Grand.Web/Controllers/VendorController.cs b/src/Web/Grand.Web/Controllers/VendorController.cs
index 43d72dcb1..b4c02297d 100644
--- a/src/Web/Grand.Web/Controllers/VendorController.cs
+++ b/src/Web/Grand.Web/Controllers/VendorController.cs
@@ -31,7 +31,7 @@ public class VendorController : BasePublicController
#region Constructors
public VendorController(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ITranslationService translationService,
ICustomerService customerService,
IMessageProviderService messageProviderService,
@@ -45,7 +45,7 @@ public class VendorController : BasePublicController
CaptchaSettings captchaSettings,
CommonSettings commonSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_translationService = translationService;
_customerService = customerService;
_messageProviderService = messageProviderService;
@@ -75,7 +75,7 @@ public class VendorController : BasePublicController
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly ITranslationService _translationService;
private readonly ICustomerService _customerService;
private readonly IMessageProviderService _messageProviderService;
@@ -101,7 +101,7 @@ public class VendorController : BasePublicController
return RedirectToRoute("HomePage");
var model = new ApplyVendorModel();
- if (!string.IsNullOrEmpty(_workContext.CurrentCustomer.VendorId))
+ if (!string.IsNullOrEmpty(_workContextAccessor.WorkContext.CurrentCustomer.VendorId))
{
//already applied for vendor account
model.DisableFormInput = true;
@@ -110,17 +110,17 @@ public class VendorController : BasePublicController
}
model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnApplyVendorPage;
- model.Email = _workContext.CurrentCustomer.Email;
+ model.Email = _workContextAccessor.WorkContext.CurrentCustomer.Email;
model.TermsOfServiceEnabled = _vendorSettings.TermsOfServiceEnabled;
model.TermsOfServicePopup = _commonSettings.PopupForTermsOfServiceLinks;
var countries =
- await _countryService.GetAllCountries(_workContext.WorkingLanguage.Id, _workContext.CurrentStore.Id);
+ await _countryService.GetAllCountries(_workContextAccessor.WorkContext.WorkingLanguage.Id, _workContextAccessor.WorkContext.CurrentStore.Id);
model.Address = await _mediator.Send(new GetVendorAddress {
- Language = _workContext.WorkingLanguage,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
Address = null,
ExcludeProperties = false,
PrePopulateWithCustomerFields = true,
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
LoadCountries = () => countries
});
@@ -164,13 +164,13 @@ public class VendorController : BasePublicController
//associate to the current customer
//but a store owner will have to manually activate this vendor
//if he wants to grant access to admin area
- _workContext.CurrentCustomer.VendorId = vendor.Id;
- await _customerService.UpdateCustomerField(_workContext.CurrentCustomer.Id, x => x.VendorId,
- _workContext.CurrentCustomer.VendorId);
+ _workContextAccessor.WorkContext.CurrentCustomer.VendorId = vendor.Id;
+ await _customerService.UpdateCustomerField(_workContextAccessor.WorkContext.CurrentCustomer.Id, x => x.VendorId,
+ _workContextAccessor.WorkContext.CurrentCustomer.VendorId);
//notify store owner here (email)
- await _messageProviderService.SendNewVendorAccountApplyStoreOwnerMessage(_workContext.CurrentCustomer,
- vendor, _workContext.CurrentStore, _languageSettings.DefaultAdminLanguageId);
+ await _messageProviderService.SendNewVendorAccountApplyStoreOwnerMessage(_workContextAccessor.WorkContext.CurrentCustomer,
+ vendor, _workContextAccessor.WorkContext.CurrentStore, _languageSettings.DefaultAdminLanguageId);
model.DisableFormInput = true;
model.Result = _translationService.GetResource("Vendors.ApplyAccount.Submitted");
@@ -182,14 +182,14 @@ public class VendorController : BasePublicController
model.TermsOfServiceEnabled = _vendorSettings.TermsOfServiceEnabled;
model.TermsOfServicePopup = _commonSettings.PopupForTermsOfServiceLinks;
var countries =
- await _countryService.GetAllCountries(_workContext.WorkingLanguage.Id, _workContext.CurrentStore.Id);
+ await _countryService.GetAllCountries(_workContextAccessor.WorkContext.WorkingLanguage.Id, _workContextAccessor.WorkContext.CurrentStore.Id);
model.Address = await _mediator.Send(new GetVendorAddress {
- Language = _workContext.WorkingLanguage,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
Address = null,
Model = model.Address,
ExcludeProperties = false,
PrePopulateWithCustomerFields = true,
- Customer = _workContext.CurrentCustomer,
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
LoadCountries = () => countries
});
return View(model);
@@ -210,7 +210,7 @@ public class VendorController : BasePublicController
if (ModelState.IsValid)
{
model = await _mediator.Send(new ContactVendorSendCommand {
- Model = model, Vendor = vendor, Store = _workContext.CurrentStore,
+ Model = model, Vendor = vendor, Store = _workContextAccessor.WorkContext.CurrentStore,
IpAddress = HttpContext.Connection.RemoteIpAddress?.ToString()
});
return Json(model);
diff --git a/src/Web/Grand.Web/Controllers/WishlistController.cs b/src/Web/Grand.Web/Controllers/WishlistController.cs
index c1ccb83a2..7c47b24b6 100644
--- a/src/Web/Grand.Web/Controllers/WishlistController.cs
+++ b/src/Web/Grand.Web/Controllers/WishlistController.cs
@@ -24,7 +24,7 @@ public class WishlistController : BasePublicController
#region Constructors
public WishlistController(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IShoppingCartService shoppingCartService,
ITranslationService translationService,
ICustomerService customerService,
@@ -32,7 +32,7 @@ public class WishlistController : BasePublicController
IMediator mediator,
ShoppingCartSettings shoppingCartSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_shoppingCartService = shoppingCartService;
_translationService = translationService;
_customerService = customerService;
@@ -45,7 +45,7 @@ public class WishlistController : BasePublicController
#region Fields
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
private readonly IShoppingCartService _shoppingCartService;
private readonly ITranslationService _translationService;
private readonly ICustomerService _customerService;
@@ -64,18 +64,18 @@ public class WishlistController : BasePublicController
if (!await _permissionService.Authorize(StandardPermission.EnableWishlist))
return Content("");
- var cart = _workContext.CurrentCustomer.ShoppingCartItems.Where(sci =>
+ var cart = _workContextAccessor.WorkContext.CurrentCustomer.ShoppingCartItems.Where(sci =>
sci.ShoppingCartTypeId == ShoppingCartType.Wishlist);
- if (!string.IsNullOrEmpty(_workContext.CurrentStore.Id))
- cart = cart.LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, _workContext.CurrentStore.Id);
+ if (!string.IsNullOrEmpty(_workContextAccessor.WorkContext.CurrentStore.Id))
+ cart = cart.LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, _workContextAccessor.WorkContext.CurrentStore.Id);
var model = await _mediator.Send(new GetMiniWishlist {
Cart = cart.ToList(),
- Customer = _workContext.CurrentCustomer,
- Language = _workContext.WorkingLanguage,
- Currency = _workContext.WorkingCurrency,
- Store = _workContext.CurrentStore
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
return Json(model);
@@ -90,23 +90,23 @@ public class WishlistController : BasePublicController
var customer = customerGuid.HasValue
? await _customerService.GetCustomerByGuid(customerGuid.Value)
- : _workContext.CurrentCustomer;
+ : _workContextAccessor.WorkContext.CurrentCustomer;
if (customer == null)
return RedirectToRoute("HomePage");
var cart = customer.ShoppingCartItems.Where(sci => sci.ShoppingCartTypeId == ShoppingCartType.Wishlist);
- if (!string.IsNullOrEmpty(_workContext.CurrentStore.Id))
- cart = cart.LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, _workContext.CurrentStore.Id);
+ if (!string.IsNullOrEmpty(_workContextAccessor.WorkContext.CurrentStore.Id))
+ cart = cart.LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, _workContextAccessor.WorkContext.CurrentStore.Id);
var model = await _mediator.Send(new GetWishlist {
Cart = cart.ToList(),
Customer = customer,
- Language = _workContext.WorkingLanguage,
- Currency = _workContext.WorkingCurrency,
- Store = _workContext.CurrentStore,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency,
+ Store = _workContextAccessor.WorkContext.CurrentStore,
IsEditable = !customerGuid.HasValue,
- TaxDisplayType = _workContext.TaxDisplayType
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType
});
return View(model);
@@ -121,12 +121,12 @@ public class WishlistController : BasePublicController
if (ModelState.IsValid)
{
var cart =
- (await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, ShoppingCartType.Wishlist))
+ (await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id, ShoppingCartType.Wishlist))
.FirstOrDefault(x => x.Id == model.ShoppingCartId);
if (cart != null)
{
var currSciWarnings = await _shoppingCartService.UpdateShoppingCartItem(
- _workContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.CurrentCustomer,
cart.Id, cart.WarehouseId, cart.Attributes, cart.EnteredPrice,
cart.RentalStartDateUtc, cart.RentalEndDateUtc,
model.Quantity);
@@ -142,7 +142,7 @@ public class WishlistController : BasePublicController
success = !warnings.Any(),
warnings = string.Join(", ", warnings),
totalproducts =
- (await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, ShoppingCartType.Wishlist))
+ (await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id, ShoppingCartType.Wishlist))
.Sum(x => x.Quantity)
});
}
@@ -159,7 +159,7 @@ public class WishlistController : BasePublicController
var pageCustomer = model.CustomerGuid.HasValue
? await _customerService.GetCustomerByGuid(model.CustomerGuid.Value)
- : _workContext.CurrentCustomer;
+ : _workContextAccessor.WorkContext.CurrentCustomer;
if (pageCustomer == null)
return Json(new { success = false, message = "Customer not found" });
@@ -170,9 +170,9 @@ public class WishlistController : BasePublicController
if (itemCart == null)
return Json(new { success = false, message = "Shopping cart ident not found" });
- var warnings = (await _shoppingCartService.AddToCart(_workContext.CurrentCustomer,
+ var warnings = (await _shoppingCartService.AddToCart(_workContextAccessor.WorkContext.CurrentCustomer,
itemCart.ProductId, ShoppingCartType.ShoppingCart,
- _workContext.CurrentStore.Id, itemCart.WarehouseId,
+ _workContextAccessor.WorkContext.CurrentStore.Id, itemCart.WarehouseId,
itemCart.Attributes, itemCart.EnteredPrice,
itemCart.RentalStartDateUtc, itemCart.RentalEndDateUtc, itemCart.Quantity,
validator: new ShoppingCartValidatorOptions { GetRequiredProductWarnings = false })).warnings;
@@ -181,7 +181,7 @@ public class WishlistController : BasePublicController
return Json(new { success = false, message = string.Join(',', warnings) });
if (_shoppingCartSettings.MoveItemsFromWishlistToCart)
- await _shoppingCartService.DeleteShoppingCartItem(_workContext.CurrentCustomer, itemCart);
+ await _shoppingCartService.DeleteShoppingCartItem(_workContextAccessor.WorkContext.CurrentCustomer, itemCart);
return Json(new { success = true, message = "" });
}
@@ -196,13 +196,13 @@ public class WishlistController : BasePublicController
if (!await _permissionService.Authorize(StandardPermission.EnableWishlist))
return Json(new { success = false, message = "No permission" });
- var itemCart = _workContext.CurrentCustomer.ShoppingCartItems
+ var itemCart = _workContextAccessor.WorkContext.CurrentCustomer.ShoppingCartItems
.FirstOrDefault(sci => sci.ShoppingCartTypeId == ShoppingCartType.Wishlist && sci.Id == shoppingCartId);
if (itemCart == null)
return Json(new { success = false, message = "Shopping cart ident not found" });
- await _shoppingCartService.DeleteShoppingCartItem(_workContext.CurrentCustomer, itemCart);
+ await _shoppingCartService.DeleteShoppingCartItem(_workContextAccessor.WorkContext.CurrentCustomer, itemCart);
return Json(new { success = true, message = "" });
}
@@ -218,16 +218,16 @@ public class WishlistController : BasePublicController
!_shoppingCartSettings.EmailWishlistEnabled)
return Content("");
- var cart = await _shoppingCartService.GetShoppingCart(_workContext.CurrentStore.Id, ShoppingCartType.Wishlist);
+ var cart = await _shoppingCartService.GetShoppingCart(_workContextAccessor.WorkContext.CurrentStore.Id, ShoppingCartType.Wishlist);
if (!cart.Any())
return Content("");
if (ModelState.IsValid)
{
//email
- await messageProviderService.SendWishlistEmailAFriendMessage(_workContext.CurrentCustomer,
- _workContext.CurrentStore,
- _workContext.WorkingLanguage.Id, model.YourEmailAddress,
+ await messageProviderService.SendWishlistEmailAFriendMessage(_workContextAccessor.WorkContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.CurrentStore,
+ _workContextAccessor.WorkContext.WorkingLanguage.Id, model.YourEmailAddress,
model.FriendEmail, FormatText.ConvertText(model.PersonalMessage));
model.SuccessfullySent = true;
diff --git a/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostCategoryHandler.cs b/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostCategoryHandler.cs
index 66c18e154..7f756c06a 100644
--- a/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostCategoryHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostCategoryHandler.cs
@@ -13,29 +13,29 @@ public class GetBlogPostCategoryHandler : IRequestHandler<GetBlogPostCategory, I
{
private readonly IBlogService _blogService;
private readonly ICacheBase _cacheBase;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public GetBlogPostCategoryHandler(IBlogService blogService, ICacheBase cacheBase,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_blogService = blogService;
_cacheBase = cacheBase;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<IList<BlogPostCategoryModel>> Handle(GetBlogPostCategory request,
CancellationToken cancellationToken)
{
- var cacheKey = string.Format(CacheKeyConst.BLOG_CATEGORY_MODEL_KEY, _workContext.WorkingLanguage.Id,
- _workContext.CurrentStore.Id);
+ var cacheKey = string.Format(CacheKeyConst.BLOG_CATEGORY_MODEL_KEY, _workContextAccessor.WorkContext.WorkingLanguage.Id,
+ _workContextAccessor.WorkContext.CurrentStore.Id);
var cachedModel = await _cacheBase.GetAsync(cacheKey, async () =>
{
var model = new List<BlogPostCategoryModel>();
- var categories = await _blogService.GetAllBlogCategories(_workContext.CurrentStore.Id);
+ var categories = await _blogService.GetAllBlogCategories(_workContextAccessor.WorkContext.CurrentStore.Id);
foreach (var item in categories)
model.Add(new BlogPostCategoryModel {
Id = item.Id,
- Name = item.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
+ Name = item.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
SeName = item.SeName,
BlogPostCount = item.BlogPosts.Count
});
diff --git a/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostHandler.cs b/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostHandler.cs
index 60cc09047..ae47936ab 100644
--- a/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostHandler.cs
@@ -27,11 +27,11 @@ public class GetBlogPostHandler : IRequestHandler<GetBlogPost, BlogPostModel>
private readonly MediaSettings _mediaSettings;
private readonly IPictureService _pictureService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public GetBlogPostHandler(
IBlogService blogService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IPictureService pictureService,
ITranslationService translationService,
IDateTimeService dateTimeService,
@@ -41,7 +41,7 @@ public class GetBlogPostHandler : IRequestHandler<GetBlogPost, BlogPostModel>
CustomerSettings customerSettings)
{
_blogService = blogService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_pictureService = pictureService;
_translationService = translationService;
_dateTimeService = dateTimeService;
@@ -59,13 +59,13 @@ public class GetBlogPostHandler : IRequestHandler<GetBlogPost, BlogPostModel>
var model = new BlogPostModel {
Id = request.BlogPost.Id,
- MetaTitle = request.BlogPost.GetTranslation(x => x.MetaTitle, _workContext.WorkingLanguage.Id),
- MetaDescription = request.BlogPost.GetTranslation(x => x.MetaDescription, _workContext.WorkingLanguage.Id),
- MetaKeywords = request.BlogPost.GetTranslation(x => x.MetaKeywords, _workContext.WorkingLanguage.Id),
- SeName = request.BlogPost.GetSeName(_workContext.WorkingLanguage.Id),
- Title = request.BlogPost.GetTranslation(x => x.Title, _workContext.WorkingLanguage.Id),
- Body = request.BlogPost.GetTranslation(x => x.Body, _workContext.WorkingLanguage.Id),
- BodyOverview = request.BlogPost.GetTranslation(x => x.BodyOverview, _workContext.WorkingLanguage.Id),
+ MetaTitle = request.BlogPost.GetTranslation(x => x.MetaTitle, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ MetaDescription = request.BlogPost.GetTranslation(x => x.MetaDescription, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ MetaKeywords = request.BlogPost.GetTranslation(x => x.MetaKeywords, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ SeName = request.BlogPost.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Title = request.BlogPost.GetTranslation(x => x.Title, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Body = request.BlogPost.GetTranslation(x => x.Body, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ BodyOverview = request.BlogPost.GetTranslation(x => x.BodyOverview, _workContextAccessor.WorkContext.WorkingLanguage.Id),
AllowComments = request.BlogPost.AllowComments,
CreatedOn = _dateTimeService.ConvertToUserTime(
request.BlogPost.StartDateUtc ?? request.BlogPost.CreatedOnUtc, DateTimeKind.Utc),
@@ -105,15 +105,15 @@ public class GetBlogPostHandler : IRequestHandler<GetBlogPost, BlogPostModel>
Title =
picture != null &&
!string.IsNullOrEmpty(
- picture.GetTranslation(x => x.TitleAttribute, _workContext.WorkingLanguage.Id))
- ? picture.GetTranslation(x => x.TitleAttribute, _workContext.WorkingLanguage.Id)
+ picture.GetTranslation(x => x.TitleAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id))
+ ? picture.GetTranslation(x => x.TitleAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id)
: string.Format(_translationService.GetResource("Media.Blog.ImageLinkTitleFormat"),
blogPost.Title),
//"alt" attribute
AlternateText =
picture != null &&
- !string.IsNullOrEmpty(picture.GetTranslation(x => x.AltAttribute, _workContext.WorkingLanguage.Id))
- ? picture.GetTranslation(x => x.AltAttribute, _workContext.WorkingLanguage.Id)
+ !string.IsNullOrEmpty(picture.GetTranslation(x => x.AltAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id))
+ ? picture.GetTranslation(x => x.AltAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id)
: string.Format(_translationService.GetResource("Media.Blog.ImageAlternateTextFormat"),
blogPost.Title)
};
diff --git a/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostListHandler.cs b/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostListHandler.cs
index a8a1d86dc..21ea87c2d 100644
--- a/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostListHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostListHandler.cs
@@ -23,11 +23,11 @@ public class GetBlogPostListHandler : IRequestHandler<GetBlogPostList, BlogPostL
private readonly MediaSettings _mediaSettings;
private readonly IPictureService _pictureService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public GetBlogPostListHandler(
IBlogService blogService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IPictureService pictureService,
ITranslationService translationService,
IDateTimeService dateTimeService,
@@ -35,7 +35,7 @@ public class GetBlogPostListHandler : IRequestHandler<GetBlogPostList, BlogPostL
MediaSettings mediaSettings)
{
_blogService = blogService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_pictureService = pictureService;
_translationService = translationService;
_dateTimeService = dateTimeService;
@@ -52,7 +52,7 @@ public class GetBlogPostListHandler : IRequestHandler<GetBlogPostList, BlogPostL
Month = request.Command.Month,
CategorySeName = request.Command.CategorySeName
},
- WorkingLanguageId = _workContext.WorkingLanguage.Id,
+ WorkingLanguageId = _workContextAccessor.WorkContext.WorkingLanguage.Id,
SearchKeyword = request.Command.SearchKeyword
};
@@ -66,18 +66,18 @@ public class GetBlogPostListHandler : IRequestHandler<GetBlogPostList, BlogPostL
if (string.IsNullOrEmpty(request.Command.CategorySeName))
{
if (string.IsNullOrEmpty(request.Command.Tag))
- blogPosts = await _blogService.GetAllBlogPosts(_workContext.CurrentStore.Id,
+ blogPosts = await _blogService.GetAllBlogPosts(_workContextAccessor.WorkContext.CurrentStore.Id,
dateFrom, dateTo, request.Command.PageNumber - 1, request.Command.PageSize,
blogPostName: model.SearchKeyword);
else
- blogPosts = await _blogService.GetAllBlogPostsByTag(_workContext.CurrentStore.Id,
+ blogPosts = await _blogService.GetAllBlogPostsByTag(_workContextAccessor.WorkContext.CurrentStore.Id,
request.Command.Tag, request.Command.PageNumber - 1, request.Command.PageSize);
}
else
{
var categoryblog = await _blogService.GetBlogCategoryBySeName(request.Command.CategorySeName);
var categoryId = categoryblog != null ? categoryblog.Id : "";
- blogPosts = await _blogService.GetAllBlogPosts(_workContext.CurrentStore.Id,
+ blogPosts = await _blogService.GetAllBlogPosts(_workContextAccessor.WorkContext.CurrentStore.Id,
dateFrom, dateTo, request.Command.PageNumber - 1, request.Command.PageSize, categoryId: categoryId,
blogPostName: model.SearchKeyword);
}
@@ -100,13 +100,13 @@ public class GetBlogPostListHandler : IRequestHandler<GetBlogPostList, BlogPostL
ArgumentNullException.ThrowIfNull(model);
model.Id = blogPost.Id;
- model.MetaTitle = blogPost.GetTranslation(x => x.MetaTitle, _workContext.WorkingLanguage.Id);
- model.MetaDescription = blogPost.GetTranslation(x => x.MetaDescription, _workContext.WorkingLanguage.Id);
- model.MetaKeywords = blogPost.GetTranslation(x => x.MetaKeywords, _workContext.WorkingLanguage.Id);
- model.SeName = blogPost.GetSeName(_workContext.WorkingLanguage.Id);
- model.Title = blogPost.GetTranslation(x => x.Title, _workContext.WorkingLanguage.Id);
- model.Body = blogPost.GetTranslation(x => x.Body, _workContext.WorkingLanguage.Id);
- model.BodyOverview = blogPost.GetTranslation(x => x.BodyOverview, _workContext.WorkingLanguage.Id);
+ model.MetaTitle = blogPost.GetTranslation(x => x.MetaTitle, _workContextAccessor.WorkContext.WorkingLanguage.Id);
+ model.MetaDescription = blogPost.GetTranslation(x => x.MetaDescription, _workContextAccessor.WorkContext.WorkingLanguage.Id);
+ model.MetaKeywords = blogPost.GetTranslation(x => x.MetaKeywords, _workContextAccessor.WorkContext.WorkingLanguage.Id);
+ model.SeName = blogPost.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id);
+ model.Title = blogPost.GetTranslation(x => x.Title, _workContextAccessor.WorkContext.WorkingLanguage.Id);
+ model.Body = blogPost.GetTranslation(x => x.Body, _workContextAccessor.WorkContext.WorkingLanguage.Id);
+ model.BodyOverview = blogPost.GetTranslation(x => x.BodyOverview, _workContextAccessor.WorkContext.WorkingLanguage.Id);
model.AllowComments = blogPost.AllowComments;
model.CreatedOn =
_dateTimeService.ConvertToUserTime(blogPost.StartDateUtc ?? blogPost.CreatedOnUtc, DateTimeKind.Utc);
@@ -134,15 +134,15 @@ public class GetBlogPostListHandler : IRequestHandler<GetBlogPostList, BlogPostL
Title =
picture != null &&
!string.IsNullOrEmpty(
- picture.GetTranslation(x => x.TitleAttribute, _workContext.WorkingLanguage.Id))
- ? picture.GetTranslation(x => x.TitleAttribute, _workContext.WorkingLanguage.Id)
+ picture.GetTranslation(x => x.TitleAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id))
+ ? picture.GetTranslation(x => x.TitleAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id)
: string.Format(_translationService.GetResource("Media.Blog.ImageLinkTitleFormat"),
blogPost.Title),
//"alt" attribute
AlternateText =
picture != null &&
- !string.IsNullOrEmpty(picture.GetTranslation(x => x.AltAttribute, _workContext.WorkingLanguage.Id))
- ? picture.GetTranslation(x => x.AltAttribute, _workContext.WorkingLanguage.Id)
+ !string.IsNullOrEmpty(picture.GetTranslation(x => x.AltAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id))
+ ? picture.GetTranslation(x => x.AltAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id)
: string.Format(_translationService.GetResource("Media.Blog.ImageAlternateTextFormat"),
blogPost.Title)
};
diff --git a/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostTagListHandler.cs b/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostTagListHandler.cs
index b101f86fe..5de34fe57 100644
--- a/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostTagListHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostTagListHandler.cs
@@ -15,27 +15,27 @@ public class GetBlogPostTagListHandler : IRequestHandler<GetBlogPostTagList, Blo
private readonly BlogSettings _blogSettings;
private readonly ICacheBase _cacheBase;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public GetBlogPostTagListHandler(IBlogService blogService, ICacheBase cacheBase, IWorkContext workContext,
+ public GetBlogPostTagListHandler(IBlogService blogService, ICacheBase cacheBase, IWorkContextAccessor workContextAccessor,
BlogSettings blogSettings)
{
_blogService = blogService;
_cacheBase = cacheBase;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_blogSettings = blogSettings;
}
public async Task<BlogPostTagListModel> Handle(GetBlogPostTagList request, CancellationToken cancellationToken)
{
- var cacheKey = string.Format(CacheKeyConst.BLOG_TAGS_MODEL_KEY, _workContext.WorkingLanguage.Id,
- _workContext.CurrentStore.Id);
+ var cacheKey = string.Format(CacheKeyConst.BLOG_TAGS_MODEL_KEY, _workContextAccessor.WorkContext.WorkingLanguage.Id,
+ _workContextAccessor.WorkContext.CurrentStore.Id);
var cachedModel = await _cacheBase.GetAsync(cacheKey, async () =>
{
var model = new BlogPostTagListModel();
//get tags
- var tags = await _blogService.GetAllBlogPostTags(_workContext.CurrentStore.Id);
+ var tags = await _blogService.GetAllBlogPostTags(_workContextAccessor.WorkContext.CurrentStore.Id);
tags = tags.OrderByDescending(x => x.BlogPostCount)
.Take(_blogSettings.NumberOfTags)
.ToList();
diff --git a/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostYearHandler.cs b/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostYearHandler.cs
index 5a74d7632..74cd92b36 100644
--- a/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostYearHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostYearHandler.cs
@@ -13,25 +13,25 @@ public class GetBlogPostYearHandler : IRequestHandler<GetBlogPostYear, IList<Blo
{
private readonly IBlogService _blogService;
private readonly ICacheBase _cacheBase;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public GetBlogPostYearHandler(IBlogService blogService, ICacheBase cacheBase,
- IWorkContext workContext)
+ IWorkContextAccessor workContextAccessor)
{
_blogService = blogService;
_cacheBase = cacheBase;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
}
public async Task<IList<BlogPostYearModel>> Handle(GetBlogPostYear request, CancellationToken cancellationToken)
{
- var cacheKey = string.Format(CacheKeyConst.BLOG_MONTHS_MODEL_KEY, _workContext.WorkingLanguage.Id,
- _workContext.CurrentStore.Id);
+ var cacheKey = string.Format(CacheKeyConst.BLOG_MONTHS_MODEL_KEY, _workContextAccessor.WorkContext.WorkingLanguage.Id,
+ _workContextAccessor.WorkContext.CurrentStore.Id);
var cachedModel = await _cacheBase.GetAsync(cacheKey, async () =>
{
var model = new List<BlogPostYearModel>();
- var blogPosts = await _blogService.GetAllBlogPosts(_workContext.CurrentStore.Id);
+ var blogPosts = await _blogService.GetAllBlogPosts(_workContextAccessor.WorkContext.CurrentStore.Id);
if (!blogPosts.Any()) return model;
var months = new SortedDictionary<DateTime, int>();
diff --git a/src/Web/Grand.Web/Features/Handlers/Blogs/GetHomePageBlogHandler.cs b/src/Web/Grand.Web/Features/Handlers/Blogs/GetHomePageBlogHandler.cs
index d66eb99ea..a21ccade8 100644
--- a/src/Web/Grand.Web/Features/Handlers/Blogs/GetHomePageBlogHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Blogs/GetHomePageBlogHandler.cs
@@ -25,10 +25,10 @@ public class GetHomePageBlogHandler : IRequestHandler<GetHomePageBlog, HomePageB
private readonly MediaSettings _mediaSettings;
private readonly IPictureService _pictureService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public GetHomePageBlogHandler(IBlogService blogService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IPictureService pictureService,
ITranslationService translationService,
IDateTimeService dateTimeService,
@@ -37,7 +37,7 @@ public class GetHomePageBlogHandler : IRequestHandler<GetHomePageBlog, HomePageB
MediaSettings mediaSettings)
{
_blogService = blogService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_pictureService = pictureService;
_translationService = translationService;
_dateTimeService = dateTimeService;
@@ -50,21 +50,21 @@ public class GetHomePageBlogHandler : IRequestHandler<GetHomePageBlog, HomePageB
public async Task<HomePageBlogItemsModel> Handle(GetHomePageBlog request, CancellationToken cancellationToken)
{
var cacheKey = string.Format(CacheKeyConst.BLOG_HOMEPAGE_MODEL_KEY,
- _workContext.WorkingLanguage.Id,
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.WorkingLanguage.Id,
+ _workContextAccessor.WorkContext.CurrentStore.Id);
var cachedModel = await _cacheBase.GetAsync(cacheKey, async () =>
{
var model = new HomePageBlogItemsModel();
- var blogPosts = await _blogService.GetAllBlogPosts(_workContext.CurrentStore.Id,
+ var blogPosts = await _blogService.GetAllBlogPosts(_workContextAccessor.WorkContext.CurrentStore.Id,
null, null, 0, _blogSettings.HomePageBlogCount);
foreach (var post in blogPosts)
{
var item = new HomePageBlogItemsModel.BlogItemModel();
- var description = post.GetTranslation(x => x.BodyOverview, _workContext.WorkingLanguage.Id);
- item.SeName = post.GetSeName(_workContext.WorkingLanguage.Id);
- item.Title = post.GetTranslation(x => x.Title, _workContext.WorkingLanguage.Id);
+ var description = post.GetTranslation(x => x.BodyOverview, _workContextAccessor.WorkContext.WorkingLanguage.Id);
+ item.SeName = post.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id);
+ item.Title = post.GetTranslation(x => x.Title, _workContextAccessor.WorkContext.WorkingLanguage.Id);
item.Short = description?.Length > _blogSettings.MaxTextSizeHomePage
? description[.._blogSettings.MaxTextSizeHomePage]
: description;
@@ -72,7 +72,7 @@ public class GetHomePageBlogHandler : IRequestHandler<GetHomePageBlog, HomePageB
_dateTimeService.ConvertToUserTime(post.StartDateUtc ?? post.CreatedOnUtc, DateTimeKind.Utc);
item.UserFields = post.UserFields;
item.Category = (await _blogService.GetBlogCategoryByPostId(post.Id)).FirstOrDefault()
- ?.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id);
+ ?.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id);
//prepare picture model
if (!string.IsNullOrEmpty(post.PictureId))
@@ -95,16 +95,16 @@ public class GetHomePageBlogHandler : IRequestHandler<GetHomePageBlog, HomePageB
//"title" attribute
pictureModel.Title =
picture != null && !string.IsNullOrEmpty(picture.GetTranslation(x => x.TitleAttribute,
- _workContext.WorkingLanguage.Id))
- ? picture.GetTranslation(x => x.TitleAttribute, _workContext.WorkingLanguage.Id)
+ _workContextAccessor.WorkContext.WorkingLanguage.Id))
+ ? picture.GetTranslation(x => x.TitleAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id)
: string.Format(_translationService.GetResource("Media.Blog.ImageLinkTitleFormat"),
post.Title);
//"alt" attribute
pictureModel.AlternateText =
picture != null &&
!string.IsNullOrEmpty(picture.GetTranslation(x => x.AltAttribute,
- _workContext.WorkingLanguage.Id))
- ? picture.GetTranslation(x => x.AltAttribute, _workContext.WorkingLanguage.Id)
+ _workContextAccessor.WorkContext.WorkingLanguage.Id))
+ ? picture.GetTranslation(x => x.AltAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id)
: string.Format(_translationService.GetResource("Media.Blog.ImageAlternateTextFormat"),
post.Title);
diff --git a/src/Web/Grand.Web/Features/Handlers/Catalog/GetCompareProductsHandler.cs b/src/Web/Grand.Web/Features/Handlers/Catalog/GetCompareProductsHandler.cs
index 2ee3e7645..2ff709e24 100644
--- a/src/Web/Grand.Web/Features/Handlers/Catalog/GetCompareProductsHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Catalog/GetCompareProductsHandler.cs
@@ -18,18 +18,18 @@ public class GetCompareProductsHandler : IRequestHandler<GetCompareProducts, Com
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IMediator _mediator;
private readonly IProductService _productService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public GetCompareProductsHandler(
IProductService productService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IAclService aclService,
IMediator mediator,
IHttpContextAccessor httpContextAccessor,
CatalogSettings catalogSettings)
{
_productService = productService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_aclService = aclService;
_mediator = mediator;
_httpContextAccessor = httpContextAccessor;
@@ -54,8 +54,8 @@ public class GetCompareProductsHandler : IRequestHandler<GetCompareProducts, Com
//ACL and store acl
products = products.Where(p =>
- _aclService.Authorize(p, _workContext.CurrentCustomer) &&
- _aclService.Authorize(p, _workContext.CurrentStore.Id)).ToList();
+ _aclService.Authorize(p, _workContextAccessor.WorkContext.CurrentCustomer) &&
+ _aclService.Authorize(p, _workContextAccessor.WorkContext.CurrentStore.Id)).ToList();
//availability dates
products = products.Where(p => p.IsAvailable()).ToList();
diff --git a/src/Web/Grand.Web/Features/Handlers/Catalog/GetSearchAutoCompleteHandler.cs b/src/Web/Grand.Web/Features/Handlers/Catalog/GetSearchAutoCompleteHandler.cs
index 20eec3b1a..e2a77ea16 100644
--- a/src/Web/Grand.Web/Features/Handlers/Catalog/GetSearchAutoCompleteHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Catalog/GetSearchAutoCompleteHandler.cs
@@ -39,7 +39,7 @@ public class GetSearchAutoCompleteHandler : IRequestHandler<GetSearchAutoComplet
private readonly IPricingService _pricingService;
private readonly ISearchTermService _searchTermService;
private readonly ITaxService _taxService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public GetSearchAutoCompleteHandler(
IPictureService pictureService,
@@ -52,7 +52,7 @@ public class GetSearchAutoCompleteHandler : IRequestHandler<GetSearchAutoComplet
ITaxService taxService,
IPriceFormatter priceFormatter,
IMediator mediator,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IPermissionService permissionService,
CatalogSettings catalogSettings,
MediaSettings mediaSettings,
@@ -66,7 +66,7 @@ public class GetSearchAutoCompleteHandler : IRequestHandler<GetSearchAutoComplet
_blogService = blogService;
_pricingService = priceCalculationService;
_taxService = taxService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_priceFormatter = priceFormatter;
_mediator = mediator;
_permissionService = permissionService;
@@ -111,10 +111,10 @@ public class GetSearchAutoCompleteHandler : IRequestHandler<GetSearchAutoComplet
var categories = new List<string>();
var brands = new List<string>();
- var storeurl = _workContext.CurrentHost.Url.TrimEnd('/');
+ var storeurl = _workContextAccessor.WorkContext.CurrentHost.Url.TrimEnd('/');
var displayPrices =
- await _permissionService.Authorize(StandardPermission.DisplayPrices, _workContext.CurrentCustomer);
+ await _permissionService.Authorize(StandardPermission.DisplayPrices, _workContextAccessor.WorkContext.CurrentCustomer);
foreach (var item in products)
{
@@ -163,7 +163,7 @@ public class GetSearchAutoCompleteHandler : IRequestHandler<GetSearchAutoComplet
if (brand is not { Published: true }) continue;
var allow = true;
if (!_accessControlConfig.IgnoreAcl)
- if (!_aclService.Authorize(brand, _workContext.CurrentCustomer))
+ if (!_aclService.Authorize(brand, _workContextAccessor.WorkContext.CurrentCustomer))
allow = false;
if (!_accessControlConfig.IgnoreStoreLimitations)
if (!_aclService.Authorize(brand, storeId))
@@ -188,7 +188,7 @@ public class GetSearchAutoCompleteHandler : IRequestHandler<GetSearchAutoComplet
if (category is not { Published: true }) continue;
var allow = true;
if (!_accessControlConfig.IgnoreAcl)
- if (!_aclService.Authorize(category, _workContext.CurrentCustomer))
+ if (!_aclService.Authorize(category, _workContextAccessor.WorkContext.CurrentCustomer))
allow = false;
if (!_accessControlConfig.IgnoreStoreLimitations)
if (!_aclService.Authorize(category, storeId))
diff --git a/src/Web/Grand.Web/Features/Handlers/Common/GetStatesProvinceHandler.cs b/src/Web/Grand.Web/Features/Handlers/Common/GetStatesProvinceHandler.cs
index 693b9f4d0..a143781c9 100644
--- a/src/Web/Grand.Web/Features/Handlers/Common/GetStatesProvinceHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Common/GetStatesProvinceHandler.cs
@@ -12,23 +12,23 @@ public class GetStatesProvinceHandler : IRequestHandler<GetStatesProvince, IList
{
private readonly ICountryService _countryService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public GetStatesProvinceHandler(ICountryService countryService, IWorkContext workContext,
+ public GetStatesProvinceHandler(ICountryService countryService, IWorkContextAccessor workContextAccessor,
ITranslationService translationService)
{
_countryService = countryService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_translationService = translationService;
}
public async Task<IList<StateProvinceModel>> Handle(GetStatesProvince request, CancellationToken cancellationToken)
{
var states =
- await _countryService.GetStateProvincesByCountryId(request.CountryId, _workContext.WorkingLanguage.Id);
+ await _countryService.GetStateProvincesByCountryId(request.CountryId, _workContextAccessor.WorkContext.WorkingLanguage.Id);
var model = (from s in states
select new StateProvinceModel
- { id = s.Id, name = s.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id) }).ToList();
+ { id = s.Id, name = s.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id) }).ToList();
if (request.AddSelectStateItem)
model.Insert(0,
new StateProvinceModel { id = "", name = _translationService.GetResource("Address.SelectState") });
diff --git a/src/Web/Grand.Web/Features/Handlers/News/GetHomePageNewsItemsHandler.cs b/src/Web/Grand.Web/Features/Handlers/News/GetHomePageNewsItemsHandler.cs
index 59cb06f0a..6335c4d74 100644
--- a/src/Web/Grand.Web/Features/Handlers/News/GetHomePageNewsItemsHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/News/GetHomePageNewsItemsHandler.cs
@@ -25,14 +25,14 @@ public class GetHomePageNewsItemsHandler : IRequestHandler<GetHomePageNewsItems,
private readonly NewsSettings _newsSettings;
private readonly IPictureService _pictureService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public GetHomePageNewsItemsHandler(ICacheBase cacheBase, IWorkContext workContext,
+ public GetHomePageNewsItemsHandler(ICacheBase cacheBase, IWorkContextAccessor workContextAccessor,
INewsService newsService, IDateTimeService dateTimeService, IPictureService pictureService,
ITranslationService translationService, NewsSettings newsSettings, MediaSettings mediaSettings)
{
_cacheBase = cacheBase;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_newsService = newsService;
_dateTimeService = dateTimeService;
_pictureService = pictureService;
@@ -43,12 +43,12 @@ public class GetHomePageNewsItemsHandler : IRequestHandler<GetHomePageNewsItems,
public async Task<HomePageNewsItemsModel> Handle(GetHomePageNewsItems request, CancellationToken cancellationToken)
{
- var cacheKey = string.Format(CacheKeyConst.HOMEPAGE_NEWSMODEL_KEY, _workContext.WorkingLanguage.Id,
- _workContext.CurrentStore.Id);
+ var cacheKey = string.Format(CacheKeyConst.HOMEPAGE_NEWSMODEL_KEY, _workContextAccessor.WorkContext.WorkingLanguage.Id,
+ _workContextAccessor.WorkContext.CurrentStore.Id);
var model = await _cacheBase.GetAsync(cacheKey, async () =>
{
var newsItems =
- await _newsService.GetAllNews(_workContext.CurrentStore.Id, 0, _newsSettings.MainPageNewsCount);
+ await _newsService.GetAllNews(_workContextAccessor.WorkContext.CurrentStore.Id, 0, _newsSettings.MainPageNewsCount);
var hpnitemodel = new HomePageNewsItemsModel();
foreach (var item in newsItems)
{
@@ -66,10 +66,10 @@ public class GetHomePageNewsItemsHandler : IRequestHandler<GetHomePageNewsItems,
{
var model = new HomePageNewsItemsModel.NewsItemModel {
Id = newsItem.Id,
- SeName = newsItem.GetSeName(_workContext.WorkingLanguage.Id),
- Title = newsItem.GetTranslation(x => x.Title, _workContext.WorkingLanguage.Id),
- Short = newsItem.GetTranslation(x => x.Short, _workContext.WorkingLanguage.Id),
- Full = newsItem.GetTranslation(x => x.Full, _workContext.WorkingLanguage.Id),
+ SeName = newsItem.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Title = newsItem.GetTranslation(x => x.Title, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Short = newsItem.GetTranslation(x => x.Short, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Full = newsItem.GetTranslation(x => x.Full, _workContextAccessor.WorkContext.WorkingLanguage.Id),
CreatedOn = _dateTimeService.ConvertToUserTime(newsItem.StartDateUtc ?? newsItem.CreatedOnUtc,
DateTimeKind.Utc)
};
diff --git a/src/Web/Grand.Web/Features/Handlers/News/GetNewsItemHandler.cs b/src/Web/Grand.Web/Features/Handlers/News/GetNewsItemHandler.cs
index 3d8e3ebe6..d78b4071b 100644
--- a/src/Web/Grand.Web/Features/Handlers/News/GetNewsItemHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/News/GetNewsItemHandler.cs
@@ -25,13 +25,13 @@ public class GetNewsItemHandler : IRequestHandler<GetNewsItem, NewsItemModel>
private readonly MediaSettings _mediaSettings;
private readonly IPictureService _pictureService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public GetNewsItemHandler(IWorkContext workContext, IDateTimeService dateTimeService,
+ public GetNewsItemHandler(IWorkContextAccessor workContextAccessor, IDateTimeService dateTimeService,
IPictureService pictureService, ITranslationService translationService, ICustomerService customerService,
MediaSettings mediaSettings, CaptchaSettings captchaSettings, CustomerSettings customerSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_dateTimeService = dateTimeService;
_pictureService = pictureService;
_translationService = translationService;
@@ -46,13 +46,13 @@ public class GetNewsItemHandler : IRequestHandler<GetNewsItem, NewsItemModel>
{
var model = new NewsItemModel {
Id = request.NewsItem.Id,
- MetaTitle = request.NewsItem.GetTranslation(x => x.MetaTitle, _workContext.WorkingLanguage.Id),
- MetaDescription = request.NewsItem.GetTranslation(x => x.MetaDescription, _workContext.WorkingLanguage.Id),
- MetaKeywords = request.NewsItem.GetTranslation(x => x.MetaKeywords, _workContext.WorkingLanguage.Id),
- SeName = request.NewsItem.GetSeName(_workContext.WorkingLanguage.Id),
- Title = request.NewsItem.GetTranslation(x => x.Title, _workContext.WorkingLanguage.Id),
- Short = request.NewsItem.GetTranslation(x => x.Short, _workContext.WorkingLanguage.Id),
- Full = request.NewsItem.GetTranslation(x => x.Full, _workContext.WorkingLanguage.Id),
+ MetaTitle = request.NewsItem.GetTranslation(x => x.MetaTitle, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ MetaDescription = request.NewsItem.GetTranslation(x => x.MetaDescription, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ MetaKeywords = request.NewsItem.GetTranslation(x => x.MetaKeywords, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ SeName = request.NewsItem.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Title = request.NewsItem.GetTranslation(x => x.Title, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Short = request.NewsItem.GetTranslation(x => x.Short, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Full = request.NewsItem.GetTranslation(x => x.Full, _workContextAccessor.WorkContext.WorkingLanguage.Id),
AllowComments = request.NewsItem.AllowComments,
CreatedOn = _dateTimeService.ConvertToUserTime(
request.NewsItem.StartDateUtc ?? request.NewsItem.CreatedOnUtc, DateTimeKind.Utc),
diff --git a/src/Web/Grand.Web/Features/Handlers/News/GetNewsItemListHandler.cs b/src/Web/Grand.Web/Features/Handlers/News/GetNewsItemListHandler.cs
index e47577642..3c931fa32 100644
--- a/src/Web/Grand.Web/Features/Handlers/News/GetNewsItemListHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/News/GetNewsItemListHandler.cs
@@ -22,13 +22,13 @@ public class GetNewsItemListHandler : IRequestHandler<GetNewsItemList, NewsItemL
private readonly NewsSettings _newsSettings;
private readonly IPictureService _pictureService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
- public GetNewsItemListHandler(IWorkContext workContext,
+ public GetNewsItemListHandler(IWorkContextAccessor workContextAccessor,
INewsService newsService, IDateTimeService dateTimeService, IPictureService pictureService,
ITranslationService translationService, NewsSettings newsSettings, MediaSettings mediaSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_newsService = newsService;
_dateTimeService = dateTimeService;
_pictureService = pictureService;
@@ -40,13 +40,13 @@ public class GetNewsItemListHandler : IRequestHandler<GetNewsItemList, NewsItemL
public async Task<NewsItemListModel> Handle(GetNewsItemList request, CancellationToken cancellationToken)
{
var model = new NewsItemListModel {
- WorkingLanguageId = _workContext.WorkingLanguage.Id
+ WorkingLanguageId = _workContextAccessor.WorkContext.WorkingLanguage.Id
};
if (request.Command.PageSize <= 0) request.Command.PageSize = _newsSettings.NewsArchivePageSize;
if (request.Command.PageNumber <= 0) request.Command.PageNumber = 1;
- var newsItems = await _newsService.GetAllNews(_workContext.CurrentStore.Id,
+ var newsItems = await _newsService.GetAllNews(_workContextAccessor.WorkContext.CurrentStore.Id,
request.Command.PageNumber - 1, request.Command.PageSize);
model.PagingFilteringContext.LoadPagedList(newsItems);
foreach (var item in newsItems)
@@ -62,10 +62,10 @@ public class GetNewsItemListHandler : IRequestHandler<GetNewsItemList, NewsItemL
{
var model = new NewsItemListModel.NewsItemModel {
Id = newsItem.Id,
- SeName = newsItem.GetSeName(_workContext.WorkingLanguage.Id),
- Title = newsItem.GetTranslation(x => x.Title, _workContext.WorkingLanguage.Id),
- Short = newsItem.GetTranslation(x => x.Short, _workContext.WorkingLanguage.Id),
- Full = newsItem.GetTranslation(x => x.Full, _workContext.WorkingLanguage.Id),
+ SeName = newsItem.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Title = newsItem.GetTranslation(x => x.Title, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Short = newsItem.GetTranslation(x => x.Short, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Full = newsItem.GetTranslation(x => x.Full, _workContextAccessor.WorkContext.WorkingLanguage.Id),
CreatedOn = _dateTimeService.ConvertToUserTime(newsItem.StartDateUtc ?? newsItem.CreatedOnUtc,
DateTimeKind.Utc)
};
diff --git a/src/Web/Grand.Web/Features/Handlers/Orders/GetMerchandiseReturnDetailsHandler.cs b/src/Web/Grand.Web/Features/Handlers/Orders/GetMerchandiseReturnDetailsHandler.cs
index 6d67133da..6281dfdf8 100644
--- a/src/Web/Grand.Web/Features/Handlers/Orders/GetMerchandiseReturnDetailsHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Orders/GetMerchandiseReturnDetailsHandler.cs
@@ -22,13 +22,13 @@ public class
private readonly OrderSettings _orderSettings;
private readonly IPriceFormatter _priceFormatter;
private readonly IProductService _productService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public GetMerchandiseReturnDetailsHandler(
IProductService productService,
IMerchandiseReturnService merchandiseReturnService,
IPriceFormatter priceFormatter,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMediator mediator,
IDateTimeService dateTimeService,
OrderSettings orderSettings)
@@ -36,7 +36,7 @@ public class
_productService = productService;
_merchandiseReturnService = merchandiseReturnService;
_priceFormatter = priceFormatter;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_mediator = mediator;
_dateTimeService = dateTimeService;
_orderSettings = orderSettings;
@@ -84,8 +84,8 @@ public class
Quantity = item.Quantity,
ReasonForReturn = item.ReasonForReturn,
RequestedAction = item.RequestedAction,
- ProductName = product.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- ProductSeName = product.GetSeName(_workContext.WorkingLanguage.Id),
+ ProductName = product.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ ProductSeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id),
ProductPrice = unitPrice
});
}
diff --git a/src/Web/Grand.Web/Features/Handlers/Orders/GetMerchandiseReturnHandler.cs b/src/Web/Grand.Web/Features/Handlers/Orders/GetMerchandiseReturnHandler.cs
index 500f26fb8..a5cd2c9fe 100644
--- a/src/Web/Grand.Web/Features/Handlers/Orders/GetMerchandiseReturnHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Orders/GetMerchandiseReturnHandler.cs
@@ -29,10 +29,10 @@ public class GetMerchandiseReturnHandler : IRequestHandler<GetMerchandiseReturn,
private readonly IProductService _productService;
private readonly IShipmentService _shipmentService;
private readonly IVendorService _vendorService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public GetMerchandiseReturnHandler(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IMerchandiseReturnService merchandiseReturnService,
IShipmentService shipmentService,
IProductService productService,
@@ -44,7 +44,7 @@ public class GetMerchandiseReturnHandler : IRequestHandler<GetMerchandiseReturn,
OrderSettings orderSettings,
ICurrencyService currencyService)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_merchandiseReturnService = merchandiseReturnService;
_shipmentService = shipmentService;
_productService = productService;
@@ -87,7 +87,7 @@ public class GetMerchandiseReturnHandler : IRequestHandler<GetMerchandiseReturn,
foreach (var rrr in await _merchandiseReturnService.GetAllMerchandiseReturnReasons())
reasons.Add(new MerchandiseReturnModel.MerchandiseReturnReasonModel {
Id = rrr.Id,
- Name = rrr.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id)
+ Name = rrr.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id)
});
return reasons;
}
@@ -98,7 +98,7 @@ public class GetMerchandiseReturnHandler : IRequestHandler<GetMerchandiseReturn,
foreach (var rra in await _merchandiseReturnService.GetAllMerchandiseReturnActions())
actions.Add(new MerchandiseReturnModel.MerchandiseReturnActionModel {
Id = rra.Id,
- Name = rra.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id)
+ Name = rra.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id)
});
return actions;
}
@@ -123,8 +123,8 @@ public class GetMerchandiseReturnHandler : IRequestHandler<GetMerchandiseReturn,
var orderItemModel = new MerchandiseReturnModel.OrderItemModel {
Id = orderItem.Id,
ProductId = orderItem.ProductId,
- ProductName = product.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- ProductSeName = product.GetSeName(_workContext.WorkingLanguage.Id),
+ ProductName = product.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ ProductSeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id),
AttributeInfo = orderItem.AttributeDescription,
VendorId = orderItem.VendorId,
VendorName = string.IsNullOrEmpty(orderItem.VendorId)
@@ -147,7 +147,7 @@ public class GetMerchandiseReturnHandler : IRequestHandler<GetMerchandiseReturn,
{
//existing addresses
var addresses = new List<Address>();
- foreach (var item in _workContext.CurrentCustomer.Addresses)
+ foreach (var item in _workContextAccessor.WorkContext.CurrentCustomer.Addresses)
{
if (string.IsNullOrEmpty(item.CountryId))
{
@@ -181,7 +181,7 @@ public class GetMerchandiseReturnHandler : IRequestHandler<GetMerchandiseReturn,
ExcludeProperties = false,
LoadCountries = () => countries,
PrePopulateWithCustomerFields = true,
- Customer = _workContext.CurrentCustomer
+ Customer = _workContextAccessor.WorkContext.CurrentCustomer
});
}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Features/Handlers/Pages/GetPageBlockHandler.cs b/src/Web/Grand.Web/Features/Handlers/Pages/GetPageBlockHandler.cs
index d6eed7c09..cc22de436 100644
--- a/src/Web/Grand.Web/Features/Handlers/Pages/GetPageBlockHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Pages/GetPageBlockHandler.cs
@@ -16,16 +16,16 @@ public class GetPageBlockHandler : IRequestHandler<GetPageBlock, PageModel>
private readonly IAclService _aclService;
private readonly IDateTimeService _dateTimeService;
private readonly IPageService _pageService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public GetPageBlockHandler(
IPageService pageService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IAclService aclService,
IDateTimeService dateTimeService)
{
_pageService = pageService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_aclService = aclService;
_dateTimeService = dateTimeService;
}
@@ -34,7 +34,7 @@ public class GetPageBlockHandler : IRequestHandler<GetPageBlock, PageModel>
{
//load by store
var page = string.IsNullOrEmpty(request.PageId)
- ? await _pageService.GetPageBySystemName(request.SystemName, _workContext.CurrentStore.Id)
+ ? await _pageService.GetPageBySystemName(request.SystemName, _workContextAccessor.WorkContext.CurrentStore.Id)
: await _pageService.GetPageById(request.PageId);
if (page is not { Published: true })
@@ -45,9 +45,9 @@ public class GetPageBlockHandler : IRequestHandler<GetPageBlock, PageModel>
return null;
//ACL (access control list)
- return !_aclService.Authorize(page, _workContext.CurrentCustomer)
+ return !_aclService.Authorize(page, _workContextAccessor.WorkContext.CurrentCustomer)
? null
- : ToModel(page, _workContext.WorkingLanguage, request.Password);
+ : ToModel(page, _workContextAccessor.WorkContext.WorkingLanguage, request.Password);
}
private PageModel ToModel(Page entity, Language language,
diff --git a/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs b/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs
index 98ea39ba8..d1885931e 100644
--- a/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs
@@ -71,11 +71,11 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
private readonly IVendorService _vendorService;
private readonly VendorSettings _vendorSettings;
private readonly IWarehouseService _warehouseService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public GetProductDetailsPageHandler(
IPermissionService permissionService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ITranslationService translationService,
IProductService productService,
IPricingService priceCalculationService,
@@ -107,7 +107,7 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
ShoppingCartSettings shoppingCartSettings)
{
_permissionService = permissionService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_translationService = translationService;
_productService = productService;
_pricingService = priceCalculationService;
@@ -191,7 +191,7 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
product.BackorderModeId == BackorderMode.NoBackorders &&
product.AllowOutOfStockSubscriptions &&
_stockQuantityService.GetTotalStockQuantity(product,
- warehouseId: _workContext.CurrentStore.DefaultWarehouseId) <= 0)
+ warehouseId: _workContextAccessor.WorkContext.CurrentStore.DefaultWarehouseId) <= 0)
//out of stock
model.DisplayOutOfStockSubscription = true;
@@ -254,7 +254,7 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
#region Product specifications
model.ProductSpecifications = await _mediator.Send(new GetProductSpecification {
- Language = _workContext.WorkingLanguage,
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
Product = product
});
@@ -264,8 +264,8 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
model.ProductReviewOverview = await _mediator.Send(new GetProductReviewOverview {
Product = product,
- Language = _workContext.WorkingLanguage,
- Store = _workContext.CurrentStore
+ Language = _workContextAccessor.WorkContext.WorkingLanguage,
+ Store = _workContextAccessor.WorkContext.CurrentStore
});
#endregion
@@ -281,17 +281,16 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
var collectionsCacheKey = string.Format(CacheKeyConst.PRODUCT_COLLECTIONS_MODEL_KEY,
product.Id,
- _workContext.WorkingLanguage.Id,
- string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.WorkingLanguage.Id,
+ string.Join(",", _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()),
+ _workContextAccessor.WorkContext.CurrentStore.Id);
model.ProductCollections = await _cacheBase.GetAsync(collectionsCacheKey, async () =>
{
var listCollection = new List<CollectionModel>();
foreach (var item in product.ProductCollections.OrderBy(x => x.DisplayOrder))
{
var collect =
- (await _collectionService.GetCollectionById(item.CollectionId)).ToModel(_workContext
- .WorkingLanguage);
+ (await _collectionService.GetCollectionById(item.CollectionId)).ToModel(_workContextAccessor.WorkContext.WorkingLanguage);
listCollection.Add(collect);
}
@@ -307,7 +306,7 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
if (!isAssociatedProduct)
{
var associatedProducts =
- await _productService.GetAssociatedProducts(product.Id, _workContext.CurrentStore.Id);
+ await _productService.GetAssociatedProducts(product.Id, _workContextAccessor.WorkContext.CurrentStore.Id);
foreach (var associatedProduct in associatedProducts)
model.AssociatedProducts.Add(
await PrepareProductDetailsModel(store, associatedProduct, null, true));
@@ -353,19 +352,19 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
var warehouseId = updateCartItem != null
? updateCartItem.WarehouseId
- : _workContext.CurrentStore.DefaultWarehouseId;
+ : _workContextAccessor.WorkContext.CurrentStore.DefaultWarehouseId;
var model = new ProductDetailsModel {
Id = product.Id,
ProductType = product.ProductTypeId,
- Name = product.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- ShortDescription = product.GetTranslation(x => x.ShortDescription, _workContext.WorkingLanguage.Id),
- FullDescription = product.GetTranslation(x => x.FullDescription, _workContext.WorkingLanguage.Id),
+ Name = product.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ ShortDescription = product.GetTranslation(x => x.ShortDescription, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ FullDescription = product.GetTranslation(x => x.FullDescription, _workContextAccessor.WorkContext.WorkingLanguage.Id),
Flag = product.Flag,
- MetaKeywords = product.GetTranslation(x => x.MetaKeywords, _workContext.WorkingLanguage.Id),
- MetaDescription = product.GetTranslation(x => x.MetaDescription, _workContext.WorkingLanguage.Id),
- MetaTitle = product.GetTranslation(x => x.MetaTitle, _workContext.WorkingLanguage.Id),
- SeName = product.GetSeName(_workContext.WorkingLanguage.Id),
+ MetaKeywords = product.GetTranslation(x => x.MetaKeywords, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ MetaDescription = product.GetTranslation(x => x.MetaDescription, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ MetaTitle = product.GetTranslation(x => x.MetaTitle, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ SeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id),
ShowSku = _catalogSettings.ShowSkuOnProductDetailsPage,
Sku = product.Sku,
ShowMpn = _catalogSettings.ShowMpn,
@@ -426,7 +425,7 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
if (deliveryDate != null)
{
model.DeliveryDate =
- deliveryDate.GetTranslation(dd => dd.Name, _workContext.WorkingLanguage.Id);
+ deliveryDate.GetTranslation(dd => dd.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id);
model.DeliveryColorSquaresRgb = deliveryDate.ColorSquaresRgb;
}
}
@@ -435,7 +434,7 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
//additional shipping charge
if (model.AdditionalShippingCharge > 0)
model.AdditionalShippingChargeStr = _priceFormatter.FormatPrice(
- (await _taxService.GetShippingPrice(model.AdditionalShippingCharge, _workContext.CurrentCustomer))
+ (await _taxService.GetShippingPrice(model.AdditionalShippingCharge, _workContextAccessor.WorkContext.CurrentCustomer))
.shippingPrice);
//ask question us on the product
@@ -444,7 +443,7 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
//store name
model.CurrentStoreName =
- _workContext.CurrentStore.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id);
+ _workContextAccessor.WorkContext.CurrentStore.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id);
return model;
@@ -460,7 +459,7 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
private async Task<ProductAskQuestionSimpleModel> PrepareProductAskQuestionSimpleModel(Product product)
{
- var customer = _workContext.CurrentCustomer;
+ var customer = _workContextAccessor.WorkContext.CurrentCustomer;
var model = new ProductAskQuestionSimpleModel {
Id = product.Id,
@@ -480,8 +479,8 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
if (brand is { Published: true })
return new BrandBriefInfoModel {
Id = brand.Id,
- Name = brand.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- SeName = brand.GetSeName(_workContext.WorkingLanguage.Id)
+ Name = brand.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ SeName = brand.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id)
};
return null;
@@ -494,8 +493,8 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
if (vendor is { Deleted: false, Active: true })
return new VendorBriefInfoModel {
Id = vendor.Id,
- Name = vendor.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- SeName = vendor.GetSeName(_workContext.WorkingLanguage.Id)
+ Name = vendor.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ SeName = vendor.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id)
};
return null;
@@ -505,16 +504,16 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
{
var breadcrumbCacheKey = string.Format(CacheKeyConst.PRODUCT_BREADCRUMB_MODEL_KEY,
product.Id,
- _workContext.WorkingLanguage.Id,
- string.Join(",", _workContext.CurrentCustomer.GetCustomerGroupIds()),
- _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.WorkingLanguage.Id,
+ string.Join(",", _workContextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupIds()),
+ _workContextAccessor.WorkContext.CurrentStore.Id);
return await _cacheBase.GetAsync(breadcrumbCacheKey, async () =>
{
var breadcrumbModel = new ProductDetailsModel.ProductBreadcrumbModel {
Enabled = _catalogSettings.CategoryBreadcrumbEnabled,
ProductId = product.Id,
- ProductName = product.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- ProductSeName = product.GetSeName(_workContext.WorkingLanguage.Id)
+ ProductName = product.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ ProductSeName = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id)
};
var productCategories = product.ProductCategories;
if (!productCategories.Any()) return breadcrumbModel;
@@ -526,8 +525,8 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
foreach (var catBr in await _categoryService.GetCategoryBreadCrumb(category))
breadcrumbModel.CategoryBreadcrumb.Add(new CategorySimpleModel {
Id = catBr.Id,
- Name = catBr.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- SeName = catBr.GetSeName(_workContext.WorkingLanguage.Id),
+ Name = catBr.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ SeName = catBr.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id),
IncludeInMenu = catBr.IncludeInMenu
});
@@ -539,7 +538,7 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
private async Task<IList<ProductTagModel>> PrepareProductTagModel(Product product)
{
var productTagsCacheKey = string.Format(CacheKeyConst.PRODUCTTAG_BY_PRODUCT_MODEL_KEY, product.Id,
- _workContext.WorkingLanguage.Id, _workContext.CurrentStore.Id);
+ _workContextAccessor.WorkContext.WorkingLanguage.Id, _workContextAccessor.WorkContext.CurrentStore.Id);
return await _cacheBase.GetAsync(productTagsCacheKey, async () =>
{
var tags = new List<ProductTagModel>();
@@ -549,7 +548,7 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
if (tag != null)
tags.Add(new ProductTagModel {
Id = tag.Id,
- Name = tag.GetTranslation(y => y.Name, _workContext.WorkingLanguage.Id),
+ Name = tag.GetTranslation(y => y.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
SeName = tag.SeName,
ProductCount = tag.Count
});
@@ -580,15 +579,15 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
Title =
picture != null &&
!string.IsNullOrEmpty(
- picture.GetTranslation(x => x.TitleAttribute, _workContext.WorkingLanguage.Id))
- ? picture.GetTranslation(x => x.TitleAttribute, _workContext.WorkingLanguage.Id)
+ picture.GetTranslation(x => x.TitleAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id))
+ ? picture.GetTranslation(x => x.TitleAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id)
: string.Format(_translationService.GetResource("Media.Product.ImageLinkTitleFormat.Details"),
name),
//"alt" attribute
AlternateText =
picture != null &&
- !string.IsNullOrEmpty(picture.GetTranslation(x => x.AltAttribute, _workContext.WorkingLanguage.Id))
- ? picture.GetTranslation(x => x.AltAttribute, _workContext.WorkingLanguage.Id)
+ !string.IsNullOrEmpty(picture.GetTranslation(x => x.AltAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id))
+ ? picture.GetTranslation(x => x.AltAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id)
: string.Format(
_translationService.GetResource("Media.Product.ImageAlternateTextFormat.Details"), name)
};
@@ -612,16 +611,16 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
//"title" attribute
Title =
!string.IsNullOrEmpty(picture.GetTranslation(x => x.TitleAttribute,
- _workContext.WorkingLanguage.Id))
- ? picture.GetTranslation(x => x.TitleAttribute, _workContext.WorkingLanguage.Id)
+ _workContextAccessor.WorkContext.WorkingLanguage.Id))
+ ? picture.GetTranslation(x => x.TitleAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id)
: string.Format(
_translationService.GetResource("Media.Product.ImageLinkTitleFormat.Details"),
name),
//"alt" attribute
AlternateText =
!string.IsNullOrEmpty(picture.GetTranslation(x => x.AltAttribute,
- _workContext.WorkingLanguage.Id))
- ? picture.GetTranslation(x => x.AltAttribute, _workContext.WorkingLanguage.Id)
+ _workContextAccessor.WorkContext.WorkingLanguage.Id))
+ ? picture.GetTranslation(x => x.AltAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id)
: string.Format(
_translationService.GetResource("Media.Product.ImageAlternateTextFormat.Details"),
name)
@@ -654,17 +653,17 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
var oldproductprice = await _taxService.GetProductPrice(product, product.OldPrice);
var oldPriceBase = oldproductprice.productprice;
var finalPriceWithoutDiscount = (await _taxService.GetProductPrice(product,
- (await _pricingService.GetFinalPrice(product, _workContext.CurrentCustomer,
- _workContext.CurrentStore,
- _workContext.WorkingCurrency, includeDiscounts: false)).finalPrice)).productprice;
+ (await _pricingService.GetFinalPrice(product, _workContextAccessor.WorkContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.CurrentStore,
+ _workContextAccessor.WorkContext.WorkingCurrency, includeDiscounts: false)).finalPrice)).productprice;
- var appliedPrice = await _pricingService.GetFinalPrice(product, _workContext.CurrentCustomer,
- _workContext.CurrentStore, _workContext.WorkingCurrency, includeDiscounts: true);
+ var appliedPrice = await _pricingService.GetFinalPrice(product, _workContextAccessor.WorkContext.CurrentCustomer,
+ _workContextAccessor.WorkContext.CurrentStore, _workContextAccessor.WorkContext.WorkingCurrency, includeDiscounts: true);
var finalPriceWithDiscount =
(await _taxService.GetProductPrice(product, appliedPrice.finalPrice)).productprice;
var oldPrice =
await _currencyService.ConvertFromPrimaryStoreCurrency(oldPriceBase,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
if (finalPriceWithoutDiscount != oldPrice && oldPrice > 0)
model.OldPrice = _priceFormatter.FormatPrice(oldPrice);
@@ -679,7 +678,7 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
{
var catalogPrice =
await _currencyService.ConvertFromPrimaryStoreCurrency(product.CatalogPrice,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
model.CatalogPrice = _priceFormatter.FormatPrice(catalogPrice);
}
@@ -690,12 +689,12 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
if (product.BasepriceEnabled)
model.BasePricePAngV = await _mediator.Send(new GetFormatBasePrice {
- Currency = _workContext.WorkingCurrency, Product = product,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency, Product = product,
ProductPrice = finalPriceWithDiscount
});
//currency code
- model.CurrencyCode = _workContext.WorkingCurrency.CurrencyCode;
+ model.CurrencyCode = _workContextAccessor.WorkContext.WorkingCurrency.CurrencyCode;
//reservation
if (product.ProductTypeId == ProductType.Reservation)
@@ -712,13 +711,13 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
model.IsAuction = true;
var highestBid =
await _currencyService.ConvertFromPrimaryStoreCurrency(product.HighestBid,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
model.HighestBid = _priceFormatter.FormatPrice(highestBid);
model.HighestBidValue = highestBid;
model.DisableBuyButton = product.DisableBuyButton;
var startPrice =
await _currencyService.ConvertFromPrimaryStoreCurrency(product.StartPrice,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
model.StartPrice = _priceFormatter.FormatPrice(startPrice);
model.StartPriceValue = startPrice;
}
@@ -792,10 +791,10 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
if (!model.EnteredPrice) return model;
var minimumCustomerEnteredPrice =
await _currencyService.ConvertFromPrimaryStoreCurrency(product.MinEnteredPrice,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
var maximumCustomerEnteredPrice =
await _currencyService.ConvertFromPrimaryStoreCurrency(product.MaxEnteredPrice,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
model.CustomerEnteredPrice = updatecartitem is { EnteredPrice: not null }
? updatecartitem.EnteredPrice.Value
@@ -820,8 +819,8 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
if (updatecartitem == null)
{
- model.SenderName = _workContext.CurrentCustomer.GetFullName();
- model.SenderEmail = _workContext.CurrentCustomer.Email;
+ model.SenderName = _workContextAccessor.WorkContext.CurrentCustomer.GetFullName();
+ model.SenderEmail = _workContextAccessor.WorkContext.CurrentCustomer.Email;
}
else
{
@@ -859,8 +858,8 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
Id = attribute.Id,
ProductId = product.Id,
ProductAttributeId = attribute.ProductAttributeId,
- Name = productAttribute.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- Description = productAttribute.GetTranslation(x => x.Description, _workContext.WorkingLanguage.Id),
+ Name = productAttribute.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ Description = productAttribute.GetTranslation(x => x.Description, _workContextAccessor.WorkContext.WorkingLanguage.Id),
TextPrompt = attribute.TextPrompt,
IsRequired = attribute.IsRequired,
AttributeControlType = attribute.AttributeControlTypeId,
@@ -899,7 +898,7 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
var valueModel = new ProductDetailsModel.ProductAttributeValueModel {
Id = attributeValue.Id,
- Name = attributeValue.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
+ Name = attributeValue.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
ColorSquaresRgb = attributeValue.ColorSquaresRgb, //used with "Color squares" attribute type
IsPreSelected = preselected,
StockAvailability = stockAvailability
@@ -919,12 +918,12 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
case > 0:
valueModel.PriceAdjustment =
"+" + _priceFormatter.FormatPrice(productprice.productprice,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
break;
case < 0:
valueModel.PriceAdjustment =
"-" + _priceFormatter.FormatPrice(-productprice.productprice,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
break;
}
@@ -1046,18 +1045,18 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
{
var model = new List<ProductDetailsModel.TierPriceModel>();
foreach (var tierPrice in product.TierPrices.OrderBy(x => x.Quantity)
- .FilterByStore(_workContext.CurrentStore.Id)
- .FilterByCurrency(_workContext.WorkingCurrency.CurrencyCode)
- .FilterForCustomer(_workContext.CurrentCustomer)
+ .FilterByStore(_workContextAccessor.WorkContext.CurrentStore.Id)
+ .FilterByCurrency(_workContextAccessor.WorkContext.WorkingCurrency.CurrencyCode)
+ .FilterForCustomer(_workContextAccessor.WorkContext.CurrentCustomer)
.FilterByDate()
.RemoveDuplicatedQuantities())
{
var tier = new ProductDetailsModel.TierPriceModel();
var priceBase = await _taxService.GetProductPrice(product, (await _pricingService.GetFinalPrice(product,
- _workContext.CurrentCustomer, _workContext.CurrentStore, _workContext.WorkingCurrency,
+ _workContextAccessor.WorkContext.CurrentCustomer, _workContextAccessor.WorkContext.CurrentStore, _workContextAccessor.WorkContext.WorkingCurrency,
0, _catalogSettings.DisplayTierPricesWithDiscounts, tierPrice.Quantity)).finalPrice);
tier.Quantity = tierPrice.Quantity;
- tier.Price = _priceFormatter.FormatPrice(priceBase.productprice, _workContext.WorkingCurrency);
+ tier.Price = _priceFormatter.FormatPrice(priceBase.productprice, _workContextAccessor.WorkContext.WorkingCurrency);
model.Add(tier);
}
@@ -1078,7 +1077,7 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
{
var reservations =
await _productReservationService.GetProductReservationsByProductId(product.Id, true, null);
- var inCart = _workContext.CurrentCustomer.ShoppingCartItems
+ var inCart = _workContextAccessor.WorkContext.CurrentCustomer.ShoppingCartItems
.Where(x => !string.IsNullOrEmpty(x.ReservationId)).ToList();
foreach (var cartItem in inCart)
{
@@ -1121,9 +1120,9 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
var bundleProduct = new ProductDetailsModel.ProductBundleModel {
ProductId = p1.Id,
- Name = p1.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- ShortDescription = p1.GetTranslation(x => x.ShortDescription, _workContext.WorkingLanguage.Id),
- SeName = p1.GetSeName(_workContext.WorkingLanguage.Id),
+ Name = p1.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ ShortDescription = p1.GetTranslation(x => x.ShortDescription, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ SeName = p1.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id),
Sku = p1.Sku,
Mpn = p1.Mpn,
Gtin = p1.Gtin,
@@ -1133,8 +1132,8 @@ public class GetProductDetailsPageHandler : IRequestHandler<GetProductDetailsPag
if (displayPrices)
{
var productprice = await _taxService.GetProductPrice(p1,
- (await _pricingService.GetFinalPrice(p1, _workContext.CurrentCustomer, _workContext.CurrentStore,
- _workContext.WorkingCurrency, includeDiscounts: true)).finalPrice);
+ (await _pricingService.GetFinalPrice(p1, _workContextAccessor.WorkContext.CurrentCustomer, _workContextAccessor.WorkContext.CurrentStore,
+ _workContextAccessor.WorkContext.WorkingCurrency, includeDiscounts: true)).finalPrice);
bundleProduct.Price = _priceFormatter.FormatPrice(productprice.productprice);
bundleProduct.PriceValue = productprice.productprice;
}
diff --git a/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.cs b/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.cs
index 516fb51f9..364330f54 100644
--- a/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.cs
@@ -35,11 +35,11 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
private readonly IPricingService _pricingService;
private readonly IProductService _productService;
private readonly ITaxService _taxService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public GetProductOverviewHandler(
IPermissionService permissionService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IProductService productService,
IBrandService brandService,
IPricingService priceCalculationService,
@@ -54,7 +54,7 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
CatalogSettings catalogSettings)
{
_permissionService = permissionService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_productService = productService;
_brandService = brandService;
_pricingService = priceCalculationService;
@@ -76,13 +76,13 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
throw new ArgumentNullException(nameof(request.Products));
var displayPrices =
- await _permissionService.Authorize(StandardPermission.DisplayPrices, _workContext.CurrentCustomer);
+ await _permissionService.Authorize(StandardPermission.DisplayPrices, _workContextAccessor.WorkContext.CurrentCustomer);
var enableShoppingCart =
- await _permissionService.Authorize(StandardPermission.EnableShoppingCart, _workContext.CurrentCustomer);
+ await _permissionService.Authorize(StandardPermission.EnableShoppingCart, _workContextAccessor.WorkContext.CurrentCustomer);
var enableWishlist =
- await _permissionService.Authorize(StandardPermission.EnableWishlist, _workContext.CurrentCustomer);
+ await _permissionService.Authorize(StandardPermission.EnableWishlist, _workContextAccessor.WorkContext.CurrentCustomer);
var pictureSize = request.ProductThumbPictureSize ?? _mediaSettings.ProductThumbPictureSize;
- var priceIncludesTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;
+ var priceIncludesTax = _workContextAccessor.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax;
var tasks = new List<Task<ProductOverviewModel>>();
@@ -115,26 +115,26 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
//specs
if (request.PrepareSpecificationAttributes && product.ProductSpecificationAttributes.Any())
model.SpecificationAttributeModels = await _mediator.Send(new GetProductSpecification
- { Language = _workContext.WorkingLanguage, Product = product });
+ { Language = _workContextAccessor.WorkContext.WorkingLanguage, Product = product });
//attributes
model.ProductAttributeModels = await PrepareAttributesModel(product);
//reviews
model.ReviewOverviewModel = await _mediator.Send(new GetProductReviewOverview
- { Product = product, Language = _workContext.WorkingLanguage, Store = _workContext.CurrentStore });
+ { Product = product, Language = _workContextAccessor.WorkContext.WorkingLanguage, Store = _workContextAccessor.WorkContext.CurrentStore });
return model;
}
private async Task<ProductOverviewModel> PrepareProductOverviewModel(Product product)
{
- var sename = product.GetSeName(_workContext.WorkingLanguage.Id);
+ var sename = product.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id);
var model = new ProductOverviewModel {
Id = product.Id,
- Name = product.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- ShortDescription = product.GetTranslation(x => x.ShortDescription, _workContext.WorkingLanguage.Id),
- FullDescription = product.GetTranslation(x => x.FullDescription, _workContext.WorkingLanguage.Id),
+ Name = product.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ ShortDescription = product.GetTranslation(x => x.ShortDescription, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ FullDescription = product.GetTranslation(x => x.FullDescription, _workContextAccessor.WorkContext.WorkingLanguage.Id),
SeName = sename,
Url = _linkGenerator.GetPathByRouteValues("Product", new { SeName = sename }),
ProductType = product.ProductTypeId,
@@ -145,11 +145,11 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
BrandName = string.IsNullOrEmpty(product.BrandId)
? ""
: (await _brandService.GetBrandById(product.BrandId))?.GetTranslation(x => x.Name,
- _workContext.WorkingLanguage.Id),
+ _workContextAccessor.WorkContext.WorkingLanguage.Id),
IsFreeShipping = product.IsFreeShipping,
LowStock = product.LowStock,
ShowSku = _catalogSettings.ShowSkuOnCatalogPages,
- TaxDisplayType = _workContext.TaxDisplayType,
+ TaxDisplayType = _workContextAccessor.WorkContext.TaxDisplayType,
Interval = product.Interval,
IntervalUnitId = product.IntervalUnitId,
EndTime = product.AvailableEndDateTimeUtc,
@@ -185,7 +185,7 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
#region Grouped product
var associatedProducts =
- await _productService.GetAssociatedProducts(product.Id, _workContext.CurrentStore.Id);
+ await _productService.GetAssociatedProducts(product.Id, _workContextAccessor.WorkContext.CurrentStore.Id);
//add to cart button (ignore "DisableBuyButton" property for grouped products)
priceModel.DisableBuyButton = !enableShoppingCart || !displayPrices;
@@ -202,8 +202,8 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
{
var catalogPrice =
await _currencyService.ConvertFromPrimaryStoreCurrency(product.CatalogPrice,
- _workContext.WorkingCurrency);
- priceModel.CatalogPrice = _priceFormatter.FormatPrice(catalogPrice, _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
+ priceModel.CatalogPrice = _priceFormatter.FormatPrice(catalogPrice, _workContextAccessor.WorkContext.WorkingCurrency);
}
if (associatedProducts.Any())
@@ -220,7 +220,7 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
{
//calculate for the maximum quantity (in case if we have tier prices)
var tmpPrice = (await _pricingService.GetFinalPrice(associatedProduct,
- _workContext.CurrentCustomer, _workContext.CurrentStore, _workContext.WorkingCurrency,
+ _workContextAccessor.WorkContext.CurrentCustomer, _workContextAccessor.WorkContext.CurrentStore, _workContextAccessor.WorkContext.WorkingCurrency,
0, true,
int.MaxValue)).finalPrice;
if (minPossiblePrice.HasValue && !(tmpPrice < minPossiblePrice.Value)) continue;
@@ -240,18 +240,18 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
//calculate prices
var finalPrice = (await _taxService.GetProductPrice(minPriceProduct,
minPossiblePrice.Value, priceIncludesTax,
- _workContext.CurrentCustomer))
+ _workContextAccessor.WorkContext.CurrentCustomer))
.productprice;
priceModel.OldPrice = null;
priceModel.Price =
- _priceFormatter.FormatPrice(finalPrice, _workContext.WorkingCurrency);
+ _priceFormatter.FormatPrice(finalPrice, _workContextAccessor.WorkContext.WorkingCurrency);
priceModel.PriceValue = finalPrice;
//PAngV base price (used in Germany)
if (product.BasepriceEnabled)
priceModel.BasePricePAngV = await _mediator.Send(new GetFormatBasePrice {
- Currency = _workContext.WorkingCurrency, Product = product,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency, Product = product,
ProductPrice = finalPrice
});
}
@@ -298,8 +298,8 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
{
var catalogPrice =
await _currencyService.ConvertFromPrimaryStoreCurrency(product.CatalogPrice,
- _workContext.WorkingCurrency);
- priceModel.CatalogPrice = _priceFormatter.FormatPrice(catalogPrice, _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
+ priceModel.CatalogPrice = _priceFormatter.FormatPrice(catalogPrice, _workContextAccessor.WorkContext.WorkingCurrency);
}
//start price for product auction
@@ -307,8 +307,8 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
{
var startPrice =
await _currencyService.ConvertFromPrimaryStoreCurrency(product.StartPrice,
- _workContext.WorkingCurrency);
- priceModel.StartPrice = _priceFormatter.FormatPrice(startPrice, _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
+ priceModel.StartPrice = _priceFormatter.FormatPrice(startPrice, _workContextAccessor.WorkContext.WorkingCurrency);
priceModel.StartPriceValue = startPrice;
}
@@ -317,8 +317,8 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
{
var highestBid =
await _currencyService.ConvertFromPrimaryStoreCurrency(product.HighestBid,
- _workContext.WorkingCurrency);
- priceModel.HighestBid = _priceFormatter.FormatPrice(highestBid, _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
+ priceModel.HighestBid = _priceFormatter.FormatPrice(highestBid, _workContextAccessor.WorkContext.WorkingCurrency);
priceModel.HighestBidValue = highestBid;
}
@@ -339,7 +339,7 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
//calculate for the maximum quantity (in case if we have tier prices)
var infoPrice = await _pricingService.GetFinalPrice(product,
- _workContext.CurrentCustomer, _workContext.CurrentStore, _workContext.WorkingCurrency,
+ _workContextAccessor.WorkContext.CurrentCustomer, _workContextAccessor.WorkContext.CurrentStore, _workContextAccessor.WorkContext.WorkingCurrency,
0, true, int.MaxValue);
priceModel.AppliedDiscounts = infoPrice.appliedDiscounts;
@@ -348,21 +348,21 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
var minPossiblePrice = infoPrice.finalPrice;
var oldPriceBase = (await _taxService.GetProductPrice(product, product.OldPrice,
- priceIncludesTax, _workContext.CurrentCustomer)).productprice;
+ priceIncludesTax, _workContextAccessor.WorkContext.CurrentCustomer)).productprice;
var finalPrice = (await _taxService.GetProductPrice(product, minPossiblePrice,
- priceIncludesTax, _workContext.CurrentCustomer)).productprice;
+ priceIncludesTax, _workContextAccessor.WorkContext.CurrentCustomer)).productprice;
var oldPrice =
await _currencyService.ConvertFromPrimaryStoreCurrency(oldPriceBase,
- _workContext.WorkingCurrency);
+ _workContextAccessor.WorkContext.WorkingCurrency);
//do we have tier prices configured?
var tierPrices = new List<TierPrice>();
if (product.TierPrices.Any())
tierPrices.AddRange(product.TierPrices.OrderBy(tp => tp.Quantity)
- .FilterByStore(_workContext.CurrentStore.Id)
- .FilterByCurrency(_workContext.WorkingCurrency.CurrencyCode)
- .FilterForCustomer(_workContext.CurrentCustomer)
+ .FilterByStore(_workContextAccessor.WorkContext.CurrentStore.Id)
+ .FilterByCurrency(_workContextAccessor.WorkContext.WorkingCurrency.CurrencyCode)
+ .FilterForCustomer(_workContextAccessor.WorkContext.CurrentCustomer)
.FilterByDate()
.RemoveDuplicatedQuantities());
@@ -374,7 +374,7 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
{
priceModel.OldPrice = null;
priceModel.Price =
- _priceFormatter.FormatPrice(finalPrice, _workContext.WorkingCurrency);
+ _priceFormatter.FormatPrice(finalPrice, _workContextAccessor.WorkContext.WorkingCurrency);
priceModel.PriceValue = finalPrice;
}
else
@@ -382,17 +382,17 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
if (!finalPrice.Equals(oldPriceBase) && oldPriceBase != 0)
{
priceModel.OldPrice =
- _priceFormatter.FormatPrice(oldPrice, _workContext.WorkingCurrency);
+ _priceFormatter.FormatPrice(oldPrice, _workContextAccessor.WorkContext.WorkingCurrency);
priceModel.OldPriceValue = oldPrice;
priceModel.Price =
- _priceFormatter.FormatPrice(finalPrice, _workContext.WorkingCurrency);
+ _priceFormatter.FormatPrice(finalPrice, _workContextAccessor.WorkContext.WorkingCurrency);
priceModel.PriceValue = finalPrice;
}
else
{
priceModel.OldPrice = null;
priceModel.Price =
- _priceFormatter.FormatPrice(finalPrice, _workContext.WorkingCurrency);
+ _priceFormatter.FormatPrice(finalPrice, _workContextAccessor.WorkContext.WorkingCurrency);
priceModel.PriceValue = finalPrice;
}
}
@@ -400,7 +400,7 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
//PAngV base price (used in Germany)
if (product.BasepriceEnabled)
priceModel.BasePricePAngV = await _mediator.Send(new GetFormatBasePrice {
- Currency = _workContext.WorkingCurrency, Product = product,
+ Currency = _workContextAccessor.WorkContext.WorkingCurrency, Product = product,
ProductPrice = finalPrice
});
}
@@ -445,15 +445,15 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
//"title" attribute
Title =
picture != null && !string.IsNullOrEmpty(picture.GetTranslation(x => x.TitleAttribute,
- _workContext.WorkingLanguage.Id))
- ? picture.GetTranslation(x => x.TitleAttribute, _workContext.WorkingLanguage.Id)
+ _workContextAccessor.WorkContext.WorkingLanguage.Id))
+ ? picture.GetTranslation(x => x.TitleAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id)
: name,
//"alt" attribute
AlternateText =
picture != null &&
!string.IsNullOrEmpty(picture.GetTranslation(x => x.AltAttribute,
- _workContext.WorkingLanguage.Id))
- ? picture.GetTranslation(x => x.AltAttribute, _workContext.WorkingLanguage.Id)
+ _workContextAccessor.WorkContext.WorkingLanguage.Id))
+ ? picture.GetTranslation(x => x.AltAttribute, _workContextAccessor.WorkContext.WorkingLanguage.Id)
: name
};
@@ -492,7 +492,7 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEn
if (pa == null) continue;
var productAttributeModel = new ProductOverviewModel.ProductAttributeModel {
- Name = pa.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
+ Name = pa.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
SeName = pa.SeName,
TextPrompt = attribute.TextPrompt,
IsRequired = attribute.IsRequired,
diff --git a/src/Web/Grand.Web/Features/Handlers/Vendors/GetVendorReviewsHandler.cs b/src/Web/Grand.Web/Features/Handlers/Vendors/GetVendorReviewsHandler.cs
index 75cdc6c77..1c3eccb89 100644
--- a/src/Web/Grand.Web/Features/Handlers/Vendors/GetVendorReviewsHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Vendors/GetVendorReviewsHandler.cs
@@ -20,10 +20,10 @@ public class GetVendorReviewsHandler : IRequestHandler<GetVendorReviews, VendorR
private readonly IGroupService _groupService;
private readonly IVendorService _vendorService;
private readonly VendorSettings _vendorSettings;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public GetVendorReviewsHandler(
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IVendorService vendorService,
ICustomerService customerService,
IDateTimeService dateTimeService,
@@ -32,7 +32,7 @@ public class GetVendorReviewsHandler : IRequestHandler<GetVendorReviews, VendorR
VendorSettings vendorSettings,
CaptchaSettings captchaSettings)
{
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
_vendorService = vendorService;
_customerService = customerService;
_dateTimeService = dateTimeService;
@@ -49,8 +49,8 @@ public class GetVendorReviewsHandler : IRequestHandler<GetVendorReviews, VendorR
var model = new VendorReviewsModel {
VendorId = request.Vendor.Id,
- VendorName = request.Vendor.GetTranslation(x => x.Name, _workContext.WorkingLanguage.Id),
- VendorSeName = request.Vendor.GetSeName(_workContext.WorkingLanguage.Id)
+ VendorName = request.Vendor.GetTranslation(x => x.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
+ VendorSeName = request.Vendor.GetSeName(_workContextAccessor.WorkContext.WorkingLanguage.Id)
};
var vendorReviews = await _vendorService.GetAllVendorReviews("", true, null, null, "", request.Vendor.Id, 0,
@@ -77,8 +77,7 @@ public class GetVendorReviewsHandler : IRequestHandler<GetVendorReviews, VendorR
}
model.AddVendorReview.CanCurrentCustomerLeaveReview = _vendorSettings.AllowAnonymousUsersToReviewVendor ||
- !await _groupService.IsGuest(_workContext
- .CurrentCustomer);
+ !await _groupService.IsGuest(_workContextAccessor.WorkContext.CurrentCustomer);
model.AddVendorReview.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnVendorReviewPage;
return model;
diff --git a/src/Web/Grand.Web/Validators/Blogs/AddBlogCommentValidator.cs b/src/Web/Grand.Web/Validators/Blogs/AddBlogCommentValidator.cs
index 3b2d91b48..e5ef90a24 100644
--- a/src/Web/Grand.Web/Validators/Blogs/AddBlogCommentValidator.cs
+++ b/src/Web/Grand.Web/Validators/Blogs/AddBlogCommentValidator.cs
@@ -22,7 +22,7 @@ public class AddBlogCommentValidator : BaseGrandValidator<AddBlogCommentModel>
CaptchaSettings captchaSettings, IHttpContextAccessor contextAccessor,
GoogleReCaptchaValidator googleReCaptchaValidator,
BlogSettings blogSettings,
- IGroupService groupService, IWorkContext workContext, IBlogService blogService, IAclService aclService,
+ IGroupService groupService, IWorkContextAccessor workContextAccessor, IBlogService blogService, IAclService aclService,
ITranslationService translationService)
: base(validators)
{
@@ -31,7 +31,7 @@ public class AddBlogCommentValidator : BaseGrandValidator<AddBlogCommentModel>
RuleFor(x => x).CustomAsync(async (x, context, _) =>
{
- if (await groupService.IsGuest(workContext.CurrentCustomer) &&
+ if (await groupService.IsGuest(workContextAccessor.WorkContext.CurrentCustomer) &&
!blogSettings.AllowNotRegisteredUsersToLeaveComments)
context.AddFailure(
translationService.GetResource("Blog.Comments.OnlyRegisteredUsersLeaveComments"));
@@ -44,7 +44,7 @@ public class AddBlogCommentValidator : BaseGrandValidator<AddBlogCommentModel>
if (blogPost is not { AllowComments: true })
context.AddFailure(translationService.GetResource("Blog.Comments.NotAllowed"));
- if (!aclService.Authorize(blogPost, workContext.CurrentStore.Id))
+ if (!aclService.Authorize(blogPost, workContextAccessor.WorkContext.CurrentStore.Id))
context.AddFailure(translationService.GetResource("Blog.Comments.NotAllowed"));
if (blogPost == null ||
diff --git a/src/Web/Grand.Web/Validators/Catalog/ProductEmailAFriendValidator.cs b/src/Web/Grand.Web/Validators/Catalog/ProductEmailAFriendValidator.cs
index 213702ce3..eb335dd9f 100644
--- a/src/Web/Grand.Web/Validators/Catalog/ProductEmailAFriendValidator.cs
+++ b/src/Web/Grand.Web/Validators/Catalog/ProductEmailAFriendValidator.cs
@@ -19,7 +19,7 @@ public class ProductEmailAFriendValidator : BaseGrandValidator<ProductEmailAFrie
IEnumerable<IValidatorConsumer<ProductEmailAFriendModel>> validators,
IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,
CaptchaSettings captchaSettings, CatalogSettings catalogSettings,
- IWorkContext workContext, IGroupService groupService, IProductService productService,
+ IWorkContextAccessor workContextAccessor, IGroupService groupService, IProductService productService,
IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator,
ITranslationService translationService)
: base(validators)
@@ -46,7 +46,7 @@ public class ProductEmailAFriendValidator : BaseGrandValidator<ProductEmailAFrie
if (product is not { Published: true } || !catalogSettings.EmailAFriendEnabled)
context.AddFailure("Product is disabled");
- if (await groupService.IsGuest(workContext.CurrentCustomer) &&
+ if (await groupService.IsGuest(workContextAccessor.WorkContext.CurrentCustomer) &&
!catalogSettings.AllowAnonymousUsersToEmailAFriend)
context.AddFailure(translationService.GetResource("Products.EmailAFriend.OnlyRegisteredUsers"));
});
diff --git a/src/Web/Grand.Web/Validators/Catalog/ProductReviewsValidator.cs b/src/Web/Grand.Web/Validators/Catalog/ProductReviewsValidator.cs
index 0cf4772fb..38a26361b 100644
--- a/src/Web/Grand.Web/Validators/Catalog/ProductReviewsValidator.cs
+++ b/src/Web/Grand.Web/Validators/Catalog/ProductReviewsValidator.cs
@@ -40,7 +40,7 @@ public class ProductReviewsValidator : BaseGrandValidator<ProductReviewsModel>
IOrderService orderService,
IProductReviewService productReviewService,
CaptchaSettings captchaSettings, CatalogSettings catalogSettings,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator,
ITranslationService translationService)
: base(validators)
@@ -65,18 +65,18 @@ public class ProductReviewsValidator : BaseGrandValidator<ProductReviewsModel>
if (product is not { Published: true } || !product.AllowCustomerReviews)
context.AddFailure("Product is disabled");
- if (await groupService.IsGuest(workContext.CurrentCustomer) &&
+ if (await groupService.IsGuest(workContextAccessor.WorkContext.CurrentCustomer) &&
!catalogSettings.AllowAnonymousUsersToReviewProduct)
context.AddFailure(translationService.GetResource("Reviews.OnlyRegisteredUsersCanWriteReviews"));
if (catalogSettings.ProductReviewPossibleOnlyAfterPurchasing &&
- !(await orderService.SearchOrders(customerId: workContext.CurrentCustomer.Id, productId: x.ProductId,
+ !(await orderService.SearchOrders(customerId: workContextAccessor.WorkContext.CurrentCustomer.Id, productId: x.ProductId,
os: (int)OrderStatusSystem.Complete)).Any())
context.AddFailure(translationService.GetResource("Reviews.ProductReviewPossibleOnlyAfterPurchasing"));
if (catalogSettings.ProductReviewPossibleOnlyOnce)
{
- var reviews = await productReviewService.GetAllProductReviews(workContext.CurrentCustomer.Id,
+ var reviews = await productReviewService.GetAllProductReviews(workContextAccessor.WorkContext.CurrentCustomer.Id,
productId: x.ProductId,
pageSize: 1);
if (reviews.Any())
diff --git a/src/Web/Grand.Web/Validators/Contact/ContactUsValidator.cs b/src/Web/Grand.Web/Validators/Contact/ContactUsValidator.cs
index c4e18e3eb..eae16747d 100644
--- a/src/Web/Grand.Web/Validators/Contact/ContactUsValidator.cs
+++ b/src/Web/Grand.Web/Validators/Contact/ContactUsValidator.cs
@@ -19,14 +19,14 @@ public class ContactUsValidator : BaseGrandValidator<ContactUsModel>
private readonly IContactAttributeParser _contactAttributeParser;
private readonly IContactAttributeService _contactAttributeService;
private readonly ITranslationService _translationService;
- private readonly IWorkContext _workContext;
+ private readonly IWorkContextAccessor _workContextAccessor;
public ContactUsValidator(
IEnumerable<IValidatorConsumer<ContactUsModel>> validators,
IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,
IContactAttributeParser contactAttributeParser,
IContactAttributeService contactAttributeService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ITranslationService translationService, CommonSettings commonSettings,
CaptchaSettings captchaSettings,
IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator)
@@ -35,7 +35,7 @@ public class ContactUsValidator : BaseGrandValidator<ContactUsModel>
_contactAttributeParser = contactAttributeParser;
_contactAttributeService = contactAttributeService;
_translationService = translationService;
- _workContext = workContext;
+ _workContextAccessor = workContextAccessor;
RuleFor(x => x.Email).NotEmpty().WithMessage(translationService.GetResource("ContactUs.Email.Required"));
RuleFor(x => x.Email).EmailAddress().WithMessage(translationService.GetResource("Common.WrongEmail"));
@@ -60,7 +60,7 @@ public class ContactUsValidator : BaseGrandValidator<ContactUsModel>
{
var contactAttributeWarnings = await GetContactAttributesWarnings(
x.Attributes.Select(z => new CustomAttribute { Key = z.Key, Value = z.Value }).ToList(),
- workContext.CurrentStore.Id);
+ workContextAccessor.WorkContext.CurrentStore.Id);
if (contactAttributeWarnings.Any())
foreach (var item in contactAttributeWarnings)
context.AddFailure(item);
@@ -99,10 +99,10 @@ public class ContactUsValidator : BaseGrandValidator<ContactUsModel>
//if not found
if (!found)
warnings.Add(
- !string.IsNullOrEmpty(a2.GetTranslation(a => a.TextPrompt, _workContext.WorkingLanguage.Id))
- ? a2.GetTranslation(a => a.TextPrompt, _workContext.WorkingLanguage.Id)
+ !string.IsNullOrEmpty(a2.GetTranslation(a => a.TextPrompt, _workContextAccessor.WorkContext.WorkingLanguage.Id))
+ ? a2.GetTranslation(a => a.TextPrompt, _workContextAccessor.WorkContext.WorkingLanguage.Id)
: string.Format(_translationService.GetResource("ContactUs.SelectAttribute"),
- a2.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id)));
+ a2.GetTranslation(a => a.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id)));
}
//now validation rules
@@ -124,7 +124,7 @@ public class ContactUsValidator : BaseGrandValidator<ContactUsModel>
if (ca.ValidationMinLength.Value > enteredTextLength)
warnings.Add(string.Format(
_translationService.GetResource("ContactUs.TextboxMinimumLength"),
- ca.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id),
+ ca.GetTranslation(a => a.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
ca.ValidationMinLength.Value));
}
}
@@ -143,7 +143,7 @@ public class ContactUsValidator : BaseGrandValidator<ContactUsModel>
if (ca.ValidationMaxLength.Value < enteredTextLength)
warnings.Add(string.Format(_translationService.GetResource("ContactUs.TextboxMaximumLength"),
- ca.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id),
+ ca.GetTranslation(a => a.Name, _workContextAccessor.WorkContext.WorkingLanguage.Id),
ca.ValidationMaxLength.Value));
}
}
diff --git a/src/Web/Grand.Web/Validators/Customer/ChangePasswordValidator.cs b/src/Web/Grand.Web/Validators/Customer/ChangePasswordValidator.cs
index 42913d9e6..01f05d11a 100644
--- a/src/Web/Grand.Web/Validators/Customer/ChangePasswordValidator.cs
+++ b/src/Web/Grand.Web/Validators/Customer/ChangePasswordValidator.cs
@@ -14,7 +14,7 @@ public class ChangePasswordValidator : BaseGrandValidator<ChangePasswordModel>
{
public ChangePasswordValidator(
IEnumerable<IValidatorConsumer<ChangePasswordModel>> validators,
- ICustomerService customerService, IWorkContext workContext, IGroupService groupService,
+ ICustomerService customerService, IWorkContextAccessor workContextAccessor, IGroupService groupService,
IEncryptionService encryptionService, ICustomerHistoryPasswordService customerHistoryPasswordService,
ICustomerManagerService customerManagerService,
ITranslationService translationService, CustomerSettings customerSettings)
@@ -38,7 +38,7 @@ public class ChangePasswordValidator : BaseGrandValidator<ChangePasswordModel>
RuleFor(x => x).CustomAsync(async (x, context, _) =>
{
- var customer = await customerService.GetCustomerById(workContext.CurrentCustomer.Id);
+ var customer = await customerService.GetCustomerById(workContextAccessor.WorkContext.CurrentCustomer.Id);
switch (customer)
{
diff --git a/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.cs b/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.cs
index a2cf97b42..391131bb3 100644
--- a/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.cs
+++ b/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.cs
@@ -16,7 +16,7 @@ public class CustomerInfoValidator : BaseGrandValidator<CustomerInfoModel>
{
public CustomerInfoValidator(
IEnumerable<IValidatorConsumer<CustomerInfoModel>> validators,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
ICustomerService customerService,
IMediator mediator, ICustomerAttributeParser customerAttributeParser,
ITranslationService translationService,
@@ -119,7 +119,7 @@ public class CustomerInfoValidator : BaseGrandValidator<CustomerInfoModel>
var customerAttributeWarnings = await customerAttributeParser.GetAttributeWarnings(customerAttributes);
foreach (var error in customerAttributeWarnings) context.AddFailure(error);
- if (workContext.CurrentCustomer.Email != x.Email.ToLower() && customerSettings.AllowUsersToChangeEmail)
+ if (workContextAccessor.WorkContext.CurrentCustomer.Email != x.Email.ToLower() && customerSettings.AllowUsersToChangeEmail)
{
if (!CommonHelper.IsValidEmail(x.Email))
context.AddFailure(
@@ -135,7 +135,7 @@ public class CustomerInfoValidator : BaseGrandValidator<CustomerInfoModel>
}
if (customerSettings.UsernamesEnabled && customerSettings.AllowUsersToChangeUsernames &&
- workContext.CurrentCustomer.Username != x.Username.ToLower())
+ workContextAccessor.WorkContext.CurrentCustomer.Username != x.Username.ToLower())
{
if (x.Username.ToLower().Length > 100)
context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.UsernameTooLong"));
diff --git a/src/Web/Grand.Web/Validators/Customer/DeleteAccountValidator.cs b/src/Web/Grand.Web/Validators/Customer/DeleteAccountValidator.cs
index 655f3b8fd..543e0e5bf 100644
--- a/src/Web/Grand.Web/Validators/Customer/DeleteAccountValidator.cs
+++ b/src/Web/Grand.Web/Validators/Customer/DeleteAccountValidator.cs
@@ -12,7 +12,7 @@ public class DeleteAccountValidator : BaseGrandValidator<DeleteAccountModel>
{
public DeleteAccountValidator(
IEnumerable<IValidatorConsumer<DeleteAccountModel>> validators,
- IEncryptionService encryptionService, CustomerSettings customerSettings, IWorkContext workContext,
+ IEncryptionService encryptionService, CustomerSettings customerSettings, IWorkContextAccessor workContextAccessor,
ITranslationService translationService)
: base(validators)
{
@@ -20,16 +20,16 @@ public class DeleteAccountValidator : BaseGrandValidator<DeleteAccountModel>
.WithMessage(translationService.GetResource("Account.DeleteAccount.Fields.Password.Required"));
RuleFor(x => x).Custom((x, context) =>
{
- var pwd = workContext.CurrentCustomer.PasswordFormatId switch {
+ var pwd = workContextAccessor.WorkContext.CurrentCustomer.PasswordFormatId switch {
PasswordFormat.Clear => x.Password,
PasswordFormat.Encrypted => encryptionService.EncryptText(x.Password,
- workContext.CurrentCustomer.PasswordSalt),
+ workContextAccessor.WorkContext.CurrentCustomer.PasswordSalt),
PasswordFormat.Hashed => encryptionService.CreatePasswordHash(x.Password,
- workContext.CurrentCustomer.PasswordSalt,
+ workContextAccessor.WorkContext.CurrentCustomer.PasswordSalt,
customerSettings.HashedPasswordFormat),
_ => throw new Exception("PasswordFormat not supported")
};
- var isValid = pwd == workContext.CurrentCustomer.Password;
+ var isValid = pwd == workContextAccessor.WorkContext.CurrentCustomer.Password;
if (!isValid) context.AddFailure(translationService.GetResource("Account.Login.WrongCredentials"));
});
}
diff --git a/src/Web/Grand.Web/Validators/Customer/RegisterValidator.cs b/src/Web/Grand.Web/Validators/Customer/RegisterValidator.cs
index 219a7227b..2756ca3c6 100644
--- a/src/Web/Grand.Web/Validators/Customer/RegisterValidator.cs
+++ b/src/Web/Grand.Web/Validators/Customer/RegisterValidator.cs
@@ -27,7 +27,7 @@ public class RegisterValidator : BaseGrandValidator<RegisterModel>
IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator,
IMediator mediator, ICustomerAttributeParser customerAttributeParser,
ICustomerService customerService,
- IGroupService groupService, IWorkContext workContext
+ IGroupService groupService, IWorkContextAccessor workContextAccessor
)
: base(validators)
{
@@ -135,7 +135,7 @@ public class RegisterValidator : BaseGrandValidator<RegisterModel>
var customerAttributeWarnings = await customerAttributeParser.GetAttributeWarnings(customerAttributes);
foreach (var error in customerAttributeWarnings) context.AddFailure(error);
- if (await groupService.IsRegistered(workContext.CurrentCustomer))
+ if (await groupService.IsRegistered(workContextAccessor.WorkContext.CurrentCustomer))
{
context.AddFailure("Current customer is already registered");
return;
diff --git a/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs b/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs
index d4b0bd260..b08e88b89 100644
--- a/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs
+++ b/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs
@@ -16,7 +16,7 @@ public class SubAccountEditValidator : BaseGrandValidator<SubAccountEditModel>
IEnumerable<IValidatorConsumer<SubAccountEditModel>> validators,
ICustomerService customerService, IGroupService groupService,
ITranslationService translationService,
- IWorkContext workContext,
+ IWorkContextAccessor workContextAccessor,
CustomerSettings customerSettings)
: base(validators)
{
@@ -54,7 +54,7 @@ public class SubAccountEditValidator : BaseGrandValidator<SubAccountEditModel>
break;
}
- if (customer != null && customer.OwnerId != workContext.CurrentCustomer.Id)
+ if (customer != null && customer.OwnerId != workContextAccessor.WorkContext.CurrentCustomer.Id)
context.AddFailure("You are not owner of this account");
if (customer != null && customer.Email != x.Email.ToLower() && customerSettings.AllowUsersToChangeEmail)
diff --git a/src/Web/Grand.Web/Validators/Knowledgebase/KnowledgebaseArticleValidator.cs b/src/Web/Grand.Web/Validators/Knowledgebase/KnowledgebaseArticleValidator.cs
index 195ec0824..37fcee8aa 100644
--- a/src/Web/Grand.Web/Validators/Knowledgebase/KnowledgebaseArticleValidator.cs
+++ b/src/Web/Grand.Web/Validators/Knowledgebase/KnowledgebaseArticleValidator.cs
@@ -18,7 +18,7 @@ public class KnowledgebaseArticleValidator : BaseGrandValidator<KnowledgebaseArt
public KnowledgebaseArticleValidator(
IEnumerable<IValidatorConsumer<KnowledgebaseArticleModel>> validators,
IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,
- IWorkContext workContext, IGroupService groupService,
+ IWorkContextAccessor workContextAccessor, IGroupService groupService,
IKnowledgebaseService knowledgebaseService, KnowledgebaseSettings knowledgebaseSettings,
CaptchaSettings captchaSettings,
IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator,
@@ -31,7 +31,7 @@ public class KnowledgebaseArticleValidator : BaseGrandValidator<KnowledgebaseArt
RuleFor(x => x).CustomAsync(async (x, context, _) =>
{
- if (await groupService.IsGuest(workContext.CurrentCustomer) &&
+ if (await groupService.IsGuest(workContextAccessor.WorkContext.CurrentCustomer) &&
!knowledgebaseSettings.AllowNotRegisteredUsersToLeaveComments)
context.AddFailure(
translationService.GetResource("Knowledgebase.Article.Comments.OnlyRegisteredUsersLeaveComments"));
diff --git a/src/Web/Grand.Web/Validators/News/AddNewsCommentValidator.cs b/src/Web/Grand.Web/Validators/News/AddNewsCommentValidator.cs
index ddb7541ea..5cdc612e5 100644
--- a/src/Web/Grand.Web/Validators/News/AddNewsCommentValidator.cs
+++ b/src/Web/Grand.Web/Validators/News/AddNewsCommentValidator.cs
@@ -18,7 +18,7 @@ public class AddNewsCommentValidator : BaseGrandValidator<AddNewsCommentModel>
public AddNewsCommentValidator(
IEnumerable<IValidatorConsumer<AddNewsCommentModel>> validators,
IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,
- IWorkContext workContext, IGroupService groupService, INewsService newsService,
+ IWorkContextAccessor workContextAccessor, IGroupService groupService, INewsService newsService,
CaptchaSettings captchaSettings, NewsSettings newsSettings,
IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator,
ITranslationService translationService)
@@ -32,7 +32,7 @@ public class AddNewsCommentValidator : BaseGrandValidator<AddNewsCommentModel>
.WithMessage(translationService.GetResource("News.Comments.CommentText.Required"));
RuleFor(x => x).CustomAsync(async (x, context, _) =>
{
- if (await groupService.IsGuest(workContext.CurrentCustomer) &&
+ if (await groupService.IsGuest(workContextAccessor.WorkContext.CurrentCustomer) &&
!newsSettings.AllowNotRegisteredUsersToLeaveComments)
context.AddFailure(translationService.GetResource("News.Comments.OnlyRegisteredUsersLeaveComments"));
var newsItem = await newsService.GetNewsById(x.Id);
diff --git a/src/Web/Grand.Web/Validators/ShoppingCart/DiscountCouponValidator.cs b/src/Web/Grand.Web/Validators/ShoppingCart/DiscountCouponValidator.cs
index d21c28807..8e0348cde 100644
--- a/src/Web/Grand.Web/Validators/ShoppingCart/DiscountCouponValidator.cs
+++ b/src/Web/Grand.Web/Validators/ShoppingCart/DiscountCouponValidator.cs
@@ -13,7 +13,7 @@ public class DiscountCouponValidator : BaseGrandValidator<DiscountCouponModel>
public DiscountCouponValidator(
IEnumerable<IValidatorConsumer<DiscountCouponModel>> validators,
IDiscountValidationService discountValidationService,
- IDiscountService discountService, IWorkContext workContext,
+ IDiscountService discountService, IWorkContextAccessor workContextAccessor,
ITranslationService translationService)
: base(validators)
{
@@ -30,7 +30,7 @@ public class DiscountCouponValidator : BaseGrandValidator<DiscountCouponModel>
if (discount is { RequiresCouponCode: true, IsEnabled: true })
{
var coupons =
- workContext.CurrentCustomer.ParseAppliedCouponCodes(SystemCustomerFieldNames.DiscountCoupons);
+ workContextAccessor.WorkContext.CurrentCustomer.ParseAppliedCouponCodes(SystemCustomerFieldNames.DiscountCoupons);
var existsAndUsed = false;
foreach (var item in coupons)
if (await discountValidationService.ExistsCodeInDiscount(item, discount.Id, null))
@@ -46,7 +46,7 @@ public class DiscountCouponValidator : BaseGrandValidator<DiscountCouponModel>
if (!existsAndUsed)
{
var validationResult = await discountValidationService.ValidateDiscount(discount,
- workContext.CurrentCustomer, workContext.CurrentStore, workContext.WorkingCurrency,
+ workContextAccessor.WorkContext.CurrentCustomer, workContextAccessor.WorkContext.CurrentStore, workContextAccessor.WorkContext.WorkingCurrency,
x.DiscountCouponCode);
if (!validationResult.IsValid)
context.AddFailure(!string.IsNullOrEmpty(validationResult.UserErrorResource)
diff --git a/src/Web/Grand.Web/Validators/ShoppingCart/GiftVoucherCouponValidator.cs b/src/Web/Grand.Web/Validators/ShoppingCart/GiftVoucherCouponValidator.cs
index 1a78d2c61..8510b606a 100644
--- a/src/Web/Grand.Web/Validators/ShoppingCart/GiftVoucherCouponValidator.cs
+++ b/src/Web/Grand.Web/Validators/ShoppingCart/GiftVoucherCouponValidator.cs
@@ -13,7 +13,7 @@ public class GiftVoucherCouponValidator : BaseGrandValidator<GiftVoucherCouponMo
{
public GiftVoucherCouponValidator(
IEnumerable<IValidatorConsumer<GiftVoucherCouponModel>> validators,
- IMediator mediator, IWorkContext workContext,
+ IMediator mediator, IWorkContextAccessor workContextAccessor,
ITranslationService translationService)
: base(validators)
{
@@ -31,8 +31,8 @@ public class GiftVoucherCouponValidator : BaseGrandValidator<GiftVoucherCouponMo
new GetGiftVoucherQuery { Code = x.GiftVoucherCouponCode, IsGiftVoucherActivated = true }, _))
.FirstOrDefault();
var isGiftVoucherValid = giftVoucher != null
- && giftVoucher.IsGiftVoucherValid(workContext.WorkingCurrency,
- workContext.CurrentStore);
+ && giftVoucher.IsGiftVoucherValid(workContextAccessor.WorkContext.WorkingCurrency,
+ workContextAccessor.WorkContext.CurrentStore);
if (!isGiftVoucherValid)
context.AddFailure(translationService.GetResource("ShoppingCart.Code.WrongGiftVoucher"));
diff --git a/src/Web/Grand.Web/Validators/ShoppingCart/UpdateQuantityValidator.cs b/src/Web/Grand.Web/Validators/ShoppingCart/UpdateQuantityValidator.cs
index 8abcf3894..b55c300c5 100644
--- a/src/Web/Grand.Web/Validators/ShoppingCart/UpdateQuantityValidator.cs
+++ b/src/Web/Grand.Web/Validators/ShoppingCart/UpdateQuantityValidator.cs
@@ -14,7 +14,7 @@ public class UpdateQuantityValidator : BaseGrandValidator<UpdateQuantityModel>
public UpdateQuantityValidator(
IEnumerable<IValidatorConsumer<UpdateQuantityModel>> validators,
IPermissionService permissionService, ShoppingCartSettings shoppingCartSettings,
- IShoppingCartService shoppingCartService, IWorkContext workContext)
+ IShoppingCartService shoppingCartService, IWorkContextAccessor workContextAccessor)
: base(validators)
{
RuleFor(x => x.Quantity).GreaterThan(0).WithMessage("Wrong quantity");
@@ -36,7 +36,7 @@ public class UpdateQuantityValidator : BaseGrandValidator<UpdateQuantityModel>
}
}
- var cart = (await shoppingCartService.GetShoppingCart(workContext.CurrentStore.Id, PrepareCartTypes()))
+ var cart = (await shoppingCartService.GetShoppingCart(workContextAccessor.WorkContext.CurrentStore.Id, PrepareCartTypes()))
.FirstOrDefault(z => z.Id == x.ShoppingCartId);
if (cart == null) context.AddFailure("Shopping cart item not found");
});
diff --git a/src/Web/Grand.Web/Validators/ShoppingCart/WishlistEmailAFriendValidator.cs b/src/Web/Grand.Web/Validators/ShoppingCart/WishlistEmailAFriendValidator.cs
index e85f332ed..5bf7eeba8 100644
--- a/src/Web/Grand.Web/Validators/ShoppingCart/WishlistEmailAFriendValidator.cs
+++ b/src/Web/Grand.Web/Validators/ShoppingCart/WishlistEmailAFriendValidator.cs
@@ -17,7 +17,7 @@ public class WishlistEmailAFriendValidator : BaseGrandValidator<WishlistEmailAFr
public WishlistEmailAFriendValidator(
IEnumerable<IValidatorConsumer<WishlistEmailAFriendModel>> validators,
IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,
- IWorkContext workContext, IGroupService groupService,
+ IWorkContextAccessor workContextAccessor, IGroupService groupService,
CaptchaSettings captchaSettings, ShoppingCartSettings shoppingCartSettings,
IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator,
ITranslationService translationService)
@@ -43,7 +43,7 @@ public class WishlistEmailAFriendValidator : BaseGrandValidator<WishlistEmailAFr
RuleFor(x => x).CustomAsync(async (x, context, _) =>
{
//check whether the current customer is guest and ia allowed to email wishlist
- if (await groupService.IsGuest(workContext.CurrentCustomer) &&
+ if (await groupService.IsGuest(workContextAccessor.WorkContext.CurrentCustomer) &&
!shoppingCartSettings.AllowAnonymousUsersToEmailWishlist)
context.AddFailure(translationService.GetResource("Wishlist.EmailAFriend.OnlyRegisteredUsers"));
});
diff --git a/src/Web/Grand.Web/Validators/Vendors/VendorReviewsValidator.cs b/src/Web/Grand.Web/Validators/Vendors/VendorReviewsValidator.cs
index 616a8e637..6fdb64439 100644
--- a/src/Web/Grand.Web/Validators/Vendors/VendorReviewsValidator.cs
+++ b/src/Web/Grand.Web/Validators/Vendors/VendorReviewsValidator.cs
@@ -22,7 +22,7 @@ public class VendorReviewsValidator : BaseGrandValidator<VendorReviewsModel>
IEnumerable<IValidatorConsumer<VendorReviewsModel>> validators,
IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,
IMediator mediator,
- IGroupService groupService, IWorkContext workContext, IVendorService vendorService,
+ IGroupService groupService, IWorkContextAccessor workContextAccessor, IVendorService vendorService,
CaptchaSettings captchaSettings, VendorSettings vendorSettings,
IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator,
ITranslationService translationService)
@@ -44,13 +44,13 @@ public class VendorReviewsValidator : BaseGrandValidator<VendorReviewsModel>
context.AddFailure(
translationService.GetResource("VendorReviews.VendorNotActiveOrAllowCustomerReviewsDisabled"));
- if (await groupService.IsGuest(workContext.CurrentCustomer) &&
+ if (await groupService.IsGuest(workContextAccessor.WorkContext.CurrentCustomer) &&
!vendorSettings.AllowAnonymousUsersToReviewVendor)
context.AddFailure(translationService.GetResource("VendorReviews.OnlyRegisteredUsersCanWriteReviews"));
//allow reviews only by customer that bought something from this vendor
if (vendorSettings.VendorReviewPossibleOnlyAfterPurchasing &&
!(await mediator.Send(new GetOrderQuery {
- CustomerId = workContext.CurrentCustomer.Id,
+ CustomerId = workContextAccessor.WorkContext.CurrentCustomer.Id,
VendorId = x.VendorId,
Os = (int)OrderStatusSystem.Complete,
PageSize = 1
@@ -61,7 +61,7 @@ public class VendorReviewsValidator : BaseGrandValidator<VendorReviewsModel>
if (vendorSettings.VendorReviewPossibleOnlyOnce)
if ((await vendorService.GetAllVendorReviews(
- workContext.CurrentCustomer.Id,
+ workContextAccessor.WorkContext.CurrentCustomer.Id,
null,
vendorId: vendor.Id,
pageSize: 1)).Any())
diff --git a/src/Web/Grand.Web/Views/Account/Reviews.cshtml b/src/Web/Grand.Web/Views/Account/Reviews.cshtml
index 1a4de2933..01834a01f 100644
--- a/src/Web/Grand.Web/Views/Account/Reviews.cshtml
+++ b/src/Web/Grand.Web/Views/Account/Reviews.cshtml
@@ -1,10 +1,10 @@
@model CustomerProductReviewsModel
@inject IPageHeadBuilder pagebuilder
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@{
Layout = "_TwoColumns";
- var supportRtl = workContext.WorkingLanguage.Rtl;
+ var supportRtl = workContextAccessor.WorkContext.WorkingLanguage.Rtl;
//title
pagebuilder.AddTitleParts(Loc["Title.Account"]);
diff --git a/src/Web/Grand.Web/Views/Checkout/Completed.cshtml b/src/Web/Grand.Web/Views/Checkout/Completed.cshtml
index 49367d3ff..42b75a38c 100644
--- a/src/Web/Grand.Web/Views/Checkout/Completed.cshtml
+++ b/src/Web/Grand.Web/Views/Checkout/Completed.cshtml
@@ -1,4 +1,4 @@
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@model CheckoutCompletedModel
@{
diff --git a/src/Web/Grand.Web/Views/Order/CustomerOrders.cshtml b/src/Web/Grand.Web/Views/Order/CustomerOrders.cshtml
index e370f425f..d08cba07c 100644
--- a/src/Web/Grand.Web/Views/Order/CustomerOrders.cshtml
+++ b/src/Web/Grand.Web/Views/Order/CustomerOrders.cshtml
@@ -1,10 +1,10 @@
@model CustomerOrderListModel
@inject IPageHeadBuilder pagebuilder
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@{
Layout = "_TwoColumns";
- var supportRtl = workContext.WorkingLanguage.Rtl;
+ var supportRtl = workContextAccessor.WorkContext.WorkingLanguage.Rtl;
//title
pagebuilder.AddTitleParts(Loc["Title.Account"]);
diff --git a/src/Web/Grand.Web/Views/Order/Details.cshtml b/src/Web/Grand.Web/Views/Order/Details.cshtml
index d2b180a3a..867a7e44f 100644
--- a/src/Web/Grand.Web/Views/Order/Details.cshtml
+++ b/src/Web/Grand.Web/Views/Order/Details.cshtml
@@ -1,9 +1,9 @@
@using System.Globalization
@model OrderDetailsModel
@inject IPageHeadBuilder pagebuilder
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@{
- var supportRtl = workContext.WorkingLanguage.Rtl;
+ var supportRtl = workContextAccessor.WorkContext.WorkingLanguage.Rtl;
Layout = "_SingleColumn";
diff --git a/src/Web/Grand.Web/Views/PdfTemplates/ShipmentPdfTemplate.cshtml b/src/Web/Grand.Web/Views/PdfTemplates/ShipmentPdfTemplate.cshtml
index 899c29b45..30ff7550d 100644
--- a/src/Web/Grand.Web/Views/PdfTemplates/ShipmentPdfTemplate.cshtml
+++ b/src/Web/Grand.Web/Views/PdfTemplates/ShipmentPdfTemplate.cshtml
@@ -6,12 +6,12 @@
@inject IOrderService _orderService
@inject IProductService _productService
@inject ICountryService _countryService
-@inject IWorkContext _workContext
+@inject IWorkContextAccessor _workContextAccessor
@inject ITranslationService _translationService
@{
- var companyName = _workContext.CurrentStore.CompanyName;
- var limitbyVendor = _workContext.CurrentVendor != null;
+ var companyName = _workContextAccessor.WorkContext.CurrentStore.CompanyName;
+ var limitbyVendor = _workContextAccessor.WorkContext.CurrentVendor != null;
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
@@ -118,7 +118,7 @@
@foreach (var item in shipment.ShipmentItems)
{
var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == item.OrderItemId);
- if (orderItem != null && (orderItem.VendorId == _workContext.CurrentVendor?.Id || !limitbyVendor))
+ if (orderItem != null && (orderItem.VendorId == _workContextAccessor.WorkContext.CurrentVendor?.Id || !limitbyVendor))
{
<tr>
<td colspan="2">
diff --git a/src/Web/Grand.Web/Views/Product/Partials/Prices.cshtml b/src/Web/Grand.Web/Views/Product/Partials/Prices.cshtml
index e33b738d0..61dba2f01 100644
--- a/src/Web/Grand.Web/Views/Product/Partials/Prices.cshtml
+++ b/src/Web/Grand.Web/Views/Product/Partials/Prices.cshtml
@@ -1,6 +1,6 @@
@using System.Globalization
@model ProductDetailsModel.ProductPriceModel
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
<div class="prices d-flex justify-content-center align-items-start row px-3 flex-column" itemprop="offers" itemscope itemtype="http://schema.org/Offer">
@if (Model.EnteredPrice)
@@ -13,7 +13,7 @@
<b-button v-b-modal.modal-1>@Loc["Products.CallForPrice"]</b-button>
<b-modal id="modal-1" hide-footer title="@Loc["Products.CallForPrice"]">
<p class="my-4">
- <span>@Loc["Products.CallForPrice"]:</span><a href="tel:@workContext.CurrentStore.CompanyPhoneNumber"> @workContext.CurrentStore.CompanyPhoneNumber</a>
+ <span>@Loc["Products.CallForPrice"]:</span><a href="tel:@workContextAccessor.WorkContext.CurrentStore.CompanyPhoneNumber"> @workContextAccessor.WorkContext.CurrentStore.CompanyPhoneNumber</a>
</p>
</b-modal>
</div>
diff --git a/src/Web/Grand.Web/Views/Shared/Components/SearchBox/Default.cshtml b/src/Web/Grand.Web/Views/Shared/Components/SearchBox/Default.cshtml
index 5c6b6c1d7..c5f9ca67a 100644
--- a/src/Web/Grand.Web/Views/Shared/Components/SearchBox/Default.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Components/SearchBox/Default.cshtml
@@ -1,9 +1,9 @@
@using Grand.Domain.Blogs
@model SearchBoxModel
@inject BlogSettings blogSettings
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@{
- var lang = workContext.WorkingLanguage.LanguageCulture;
+ var lang = workContextAccessor.WorkContext.WorkingLanguage.LanguageCulture;
}
<template id="searchBoxContainer">
<a class="modal-close" @@click="$bvModal.hide('search-box')">
diff --git a/src/Web/Grand.Web/Views/Shared/Components/VoiceNavigation/Default.cshtml b/src/Web/Grand.Web/Views/Shared/Components/VoiceNavigation/Default.cshtml
index ce8e7ca2b..db3f5485a 100644
--- a/src/Web/Grand.Web/Views/Shared/Components/VoiceNavigation/Default.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Components/VoiceNavigation/Default.cshtml
@@ -1,6 +1,6 @@
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@{
- var lang = workContext.WorkingLanguage.LanguageCulture;
+ var lang = workContextAccessor.WorkContext.WorkingLanguage.LanguageCulture;
}
<template v-if="voicenavigator.allowed">
<button id="voicePageButton"
diff --git a/src/Web/Grand.Web/Views/Shared/Partials/Cookie.cshtml b/src/Web/Grand.Web/Views/Shared/Partials/Cookie.cshtml
index 9daacf209..40fd77dd8 100644
--- a/src/Web/Grand.Web/Views/Shared/Partials/Cookie.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Partials/Cookie.cshtml
@@ -1,9 +1,9 @@
@inject StoreInformationSettings storeInformationSettings
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
-@if (storeInformationSettings.DisplayCookieInformation && !workContext.CurrentCustomer.IsSystemAccount)
+@if (storeInformationSettings.DisplayCookieInformation && !workContextAccessor.WorkContext.CurrentCustomer.IsSystemAccount)
{
- if (workContext.CurrentCustomer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.CookieAccepted, workContext.CurrentStore.Id))
+ if (workContextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.CookieAccepted, workContextAccessor.WorkContext.CurrentStore.Id))
return;
if (TempData["Grand.IgnoreCookieInformation"] != null && Convert.ToBoolean(TempData["Grand.IgnoreCookieInformation"]))
diff --git a/src/Web/Grand.Web/Views/Shared/Partials/Head.cshtml b/src/Web/Grand.Web/Views/Shared/Partials/Head.cshtml
index 63b9677b9..2f5a399b0 100644
--- a/src/Web/Grand.Web/Views/Shared/Partials/Head.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Partials/Head.cshtml
@@ -1,7 +1,7 @@
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@{
- var supportRtl = workContext.WorkingLanguage.Rtl;
+ var supportRtl = workContextAccessor.WorkContext.WorkingLanguage.Rtl;
<script asp-location="Head" src="/bundles/app.runtime.bundle.js"></script>
<script asp-location="Head" src="/bundles/chunk-vendors.runtime.bundle.js"></script>
diff --git a/src/Web/Grand.Web/Views/Shared/Partials/Header.cshtml b/src/Web/Grand.Web/Views/Shared/Partials/Header.cshtml
index 0e93dbc48..40d994716 100644
--- a/src/Web/Grand.Web/Views/Shared/Partials/Header.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Partials/Header.cshtml
@@ -1,8 +1,8 @@
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@inject StoreInformationSettings StoreInformationSettings
@inject CommonSettings CommonSettings
@{
- var supportRtl = workContext.WorkingLanguage.Rtl;
+ var supportRtl = workContextAccessor.WorkContext.WorkingLanguage.Rtl;
}
<div class="header-nav">
<nav class="navbar navbar-light navbar-expand">
diff --git a/src/Web/Grand.Web/Views/Shared/Partials/HeaderLinks.cshtml b/src/Web/Grand.Web/Views/Shared/Partials/HeaderLinks.cshtml
index 4c3935265..fb12a92eb 100644
--- a/src/Web/Grand.Web/Views/Shared/Partials/HeaderLinks.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Partials/HeaderLinks.cshtml
@@ -2,15 +2,15 @@
@using Grand.Business.Core.Interfaces.Common.Security
@using Grand.Domain.Permissions
@inject IGroupService groupService
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@inject IPageHeadBuilder pagebuilder
@inject IPermissionService permissionService
@{
var registerUrl = Url.RouteUrl("Register", new { returnUrl = Context.Request.Query["returnUrl"] });
- var isAuthenticated = await groupService.IsRegistered(workContext.CurrentCustomer);
- var isCustomerImpersonated = workContext.OriginalCustomerIfImpersonated != null;
+ var isAuthenticated = await groupService.IsRegistered(workContextAccessor.WorkContext.CurrentCustomer);
+ var isCustomerImpersonated = workContextAccessor.WorkContext.OriginalCustomerIfImpersonated != null;
var isAdminAccess = await permissionService.Authorize(StandardPermission.ManageAccessAdminPanel);
- var isVendor = workContext.CurrentVendor != null;
+ var isVendor = workContextAccessor.WorkContext.CurrentVendor != null;
}
@await Component.InvokeAsync("Widget", new { widgetZone = "header_links_before" })
@@ -19,7 +19,7 @@
{
<a class="btn btn-outline-secondary w-100 mb-2" href="@Url.RouteUrl("Logout")" title="@Loc["Account.ImpersonatedAs.Finish.Hint"]">
<b-icon icon="door-closed"></b-icon>
- <span class="text text-uppercase ml-3">@string.Format(Loc["Account.ImpersonatedAs"], workContext.CurrentCustomer.Email ?? "GUEST")</span>
+ <span class="text text-uppercase ml-3">@string.Format(Loc["Account.ImpersonatedAs"], workContextAccessor.WorkContext.CurrentCustomer.Email ?? "GUEST")</span>
</a>
}
@if (isAuthenticated)
diff --git a/src/Web/Grand.Web/Views/Shared/Partials/Logo.cshtml b/src/Web/Grand.Web/Views/Shared/Partials/Logo.cshtml
index c6ad5ae22..bd8de8193 100644
--- a/src/Web/Grand.Web/Views/Shared/Partials/Logo.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Partials/Logo.cshtml
@@ -1,11 +1,11 @@
@using Grand.Business.Core.Interfaces.Storage
@inject StoreInformationSettings storeInformation
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@inject IPictureService pictureService
@{
var urlLogo = await pictureService.GetPictureUrl(storeInformation.LogoPictureId);
}
<a class="navbar-brand store-logo mx-lg-0 mx-auto" target="_self" href="@Url.RouteUrl("HomePage")">
- <img width="236" height="53" src="@urlLogo" alt="@workContext.CurrentStore.Name"/>
+ <img width="236" height="53" src="@urlLogo" alt="@workContextAccessor.WorkContext.CurrentStore.Name" />
<span class="sr-only">@Loc["Logo"]</span>
</a>
\ No newline at end of file
diff --git a/src/Web/Grand.Web/Views/Shared/Partials/Selector_Currency.cshtml b/src/Web/Grand.Web/Views/Shared/Partials/Selector_Currency.cshtml
index 582dd3adf..5f6dd6701 100644
--- a/src/Web/Grand.Web/Views/Shared/Partials/Selector_Currency.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Partials/Selector_Currency.cshtml
@@ -2,10 +2,10 @@
@using Grand.Business.Core.Extensions
@using Grand.Business.Core.Interfaces.Common.Directory
@inject ICurrencyService currencyService
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@{
- var availableCurrencies = (await currencyService.GetAllCurrencies(storeId: workContext.CurrentStore.Id))
+ var availableCurrencies = (await currencyService.GetAllCurrencies(storeId: workContextAccessor.WorkContext.CurrentStore.Id))
.Select(x =>
{
//currency char
@@ -15,7 +15,7 @@
var currencyModel = new CurrencyModel
{
Id = x.Id,
- Name = x.GetTranslation(y => y.Name, workContext.WorkingLanguage.Id),
+ Name = x.GetTranslation(y => y.Name, workContextAccessor.WorkContext.WorkingLanguage.Id),
CurrencyCode = x.CurrencyCode,
CurrencySymbol = currencySymbol
};
@@ -30,7 +30,7 @@
x.Name,
Text = x.CurrencyCode,
Value = Url.RouteUrl("ChangeCurrency", new { currencyCode = x.CurrencyCode, returnUrl }),
- Selected = x.Id.Equals(workContext.WorkingCurrency.Id)
+ Selected = x.Id.Equals(workContextAccessor.WorkContext.WorkingCurrency.Id)
});
<b-dropdown class="mr-2" text="@currencies.FirstOrDefault(x => x.Selected).Text">
@foreach (var item in currencies)
diff --git a/src/Web/Grand.Web/Views/Shared/Partials/Selector_Language.cshtml b/src/Web/Grand.Web/Views/Shared/Partials/Selector_Language.cshtml
index c896a877a..562fd5265 100644
--- a/src/Web/Grand.Web/Views/Shared/Partials/Selector_Language.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Partials/Selector_Language.cshtml
@@ -1,8 +1,8 @@
@using Grand.Business.Core.Interfaces.Common.Localization
@inject ILanguageService languageService
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@{
- var availableLanguages = (await languageService.GetAllLanguages(storeId: workContext.CurrentStore.Id))
+ var availableLanguages = (await languageService.GetAllLanguages(storeId: workContextAccessor.WorkContext.CurrentStore.Id))
.Select(x => new LanguageModel
{
Id = x.Id,
@@ -16,10 +16,10 @@
if (availableLanguages.Count > 1)
{
<div>
- <b-dropdown class="mr-2" text="@availableLanguages.FirstOrDefault(x => x.Id == workContext.WorkingLanguage.Id)?.Name">
+ <b-dropdown class="mr-2" text="@availableLanguages.FirstOrDefault(x => x.Id == workContextAccessor.WorkContext.WorkingLanguage.Id)?.Name">
@foreach (var lang in availableLanguages)
{
- var className = lang.Id == workContext.WorkingLanguage.Id ? "active" : "";
+ var className = lang.Id == workContextAccessor.WorkContext.WorkingLanguage.Id ? "active" : "";
<b-dropdown-item class="@className" href="@Url.RouteUrl("ChangeLanguage", new { langcode = lang.UniqueSeoCode, returnurl })">
@lang.Name
</b-dropdown-item>
diff --git a/src/Web/Grand.Web/Views/Shared/Partials/Selector_Store.cshtml b/src/Web/Grand.Web/Views/Shared/Partials/Selector_Store.cshtml
index 8814483b1..865501531 100644
--- a/src/Web/Grand.Web/Views/Shared/Partials/Selector_Store.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Partials/Selector_Store.cshtml
@@ -1,16 +1,16 @@
@using Grand.Business.Core.Extensions
@using Grand.Business.Core.Interfaces.Common.Stores
@inject IStoreService StoreService
-@inject IWorkContext WorkContext
+@inject IWorkContextAccessor workContextAccessor
@{
- var availableStores = StoreService.GetAll()
+ var availableStores = (await StoreService.GetAllStores())
.Select(x =>
{
//model
var storeModel = new StoreModel
{
Id = x.Id,
- Name = x.GetTranslation(y => y.Name, WorkContext.WorkingLanguage.Id),
+ Name = x.GetTranslation(y => y.Name, workContextAccessor.WorkContext.WorkingLanguage.Id),
Shortcut = x.Shortcut
};
return storeModel;
@@ -20,10 +20,10 @@
{
var returnUrl = Context?.Request?.GetEncodedPathAndQuery();
- <b-dropdown class="mr-2" text="@availableStores.FirstOrDefault(x => x.Id == WorkContext.CurrentStore.Id)?.Name">
+ <b-dropdown class="mr-2" text="@availableStores.FirstOrDefault(x => x.Id == workContextAccessor.WorkContext.CurrentStore.Id)?.Name">
@foreach (var store in availableStores)
{
- var className = store.Id == WorkContext.CurrentStore.Id ? "active" : "";
+ var className = store.Id == workContextAccessor.WorkContext.CurrentStore.Id ? "active" : "";
<b-dropdown-item class="@className" href="@Url.RouteUrl("ChangeStore", new { shortcut = store.Shortcut, returnUrl })">
@store.Name
</b-dropdown-item>
diff --git a/src/Web/Grand.Web/Views/Shared/Partials/Selector_TaxType.cshtml b/src/Web/Grand.Web/Views/Shared/Partials/Selector_TaxType.cshtml
index 98b270ffb..3b9ba1182 100644
--- a/src/Web/Grand.Web/Views/Shared/Partials/Selector_TaxType.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Partials/Selector_TaxType.cshtml
@@ -1,12 +1,12 @@
@inject TaxSettings taxSettings
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@if (taxSettings.AllowCustomersToSelectTaxDisplayType)
{
var text = "";
var className = "";
var returnUrl = Context?.Request?.GetEncodedPathAndQuery();
- if (workContext.TaxDisplayType == TaxDisplayType.IncludingTax)
+ if (workContextAccessor.WorkContext.TaxDisplayType == TaxDisplayType.IncludingTax)
{
text = Loc["Tax.Inclusive"];
className = "active";
diff --git a/src/Web/Grand.Web/Views/Shared/Partials/ShoppingCartLinks.cshtml b/src/Web/Grand.Web/Views/Shared/Partials/ShoppingCartLinks.cshtml
index 424e2f6c6..decccb59a 100644
--- a/src/Web/Grand.Web/Views/Shared/Partials/ShoppingCartLinks.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Partials/ShoppingCartLinks.cshtml
@@ -1,7 +1,7 @@
@using Grand.Business.Core.Interfaces.Checkout.Orders
@using Grand.Business.Core.Interfaces.Common.Security
@using Grand.Domain.Permissions
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@inject IPermissionService permissionService
@inject IShoppingCartService shoppingCartService
@inject ShoppingCartSettings shoppingCartSettings
@@ -20,14 +20,14 @@
var miniShoppingCartEnabled = shoppingCartSettings.MiniShoppingCartEnabled;
var shoppingCartItems =
- workContext.CurrentCustomer.ShoppingCartItems.Any()
- ? (await shoppingCartService.GetShoppingCart(workContext.CurrentStore.Id, shoppingCartTypes.ToArray()))
+ workContextAccessor.WorkContext.CurrentCustomer.ShoppingCartItems.Any()
+ ? (await shoppingCartService.GetShoppingCart(workContextAccessor.WorkContext.CurrentStore.Id, shoppingCartTypes.ToArray()))
.Sum(x => x.Quantity)
: 0;
- var wishlistItems = workContext.CurrentCustomer.ShoppingCartItems.Any()
- ? (await shoppingCartService.GetShoppingCart(workContext.CurrentStore.Id, ShoppingCartType.Wishlist))
+ var wishlistItems = workContextAccessor.WorkContext.CurrentCustomer.ShoppingCartItems.Any()
+ ? (await shoppingCartService.GetShoppingCart(workContextAccessor.WorkContext.CurrentStore.Id, ShoppingCartType.Wishlist))
.Sum(x => x.Quantity)
: 0;
}
diff --git a/src/Web/Grand.Web/Views/Shared/Partials/SidebarCompareProducts.cshtml b/src/Web/Grand.Web/Views/Shared/Partials/SidebarCompareProducts.cshtml
index 0793c88a5..5fefd396a 100644
--- a/src/Web/Grand.Web/Views/Shared/Partials/SidebarCompareProducts.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Partials/SidebarCompareProducts.cshtml
@@ -1,6 +1,6 @@
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@{
- var supportRtl = workContext.WorkingLanguage.Rtl;
+ var supportRtl = workContextAccessor.WorkContext.WorkingLanguage.Rtl;
}
<li class="nav-item">
<ul class="px-0">
diff --git a/src/Web/Grand.Web/Views/Shared/Partials/SidebarShoppingCart.cshtml b/src/Web/Grand.Web/Views/Shared/Partials/SidebarShoppingCart.cshtml
index 322d75c14..983f232e9 100644
--- a/src/Web/Grand.Web/Views/Shared/Partials/SidebarShoppingCart.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Partials/SidebarShoppingCart.cshtml
@@ -1,7 +1,7 @@
@model int
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@{
- var supportRtl = workContext.WorkingLanguage.Rtl;
+ var supportRtl = workContextAccessor.WorkContext.WorkingLanguage.Rtl;
}
<li class="nav-item">
<ul class="sidebar-cart px-0">
diff --git a/src/Web/Grand.Web/Views/Shared/Partials/SidebarWishlist.cshtml b/src/Web/Grand.Web/Views/Shared/Partials/SidebarWishlist.cshtml
index dd242e317..7be64da9c 100644
--- a/src/Web/Grand.Web/Views/Shared/Partials/SidebarWishlist.cshtml
+++ b/src/Web/Grand.Web/Views/Shared/Partials/SidebarWishlist.cshtml
@@ -1,7 +1,7 @@
@model int
-@inject IWorkContext workContext
+@inject IWorkContextAccessor workContextAccessor
@{
- var supportRtl = workContext.WorkingLanguage.Rtl;
+ var supportRtl = workContextAccessor.WorkContext.WorkingLanguage.Rtl;
}
<li class="nav-item">
<ul class="sidebar-cart wishlist px-0">