Here I feel if there an admin utility factory exist, which provide these utilities then I did not need to write the methods again.
The factory can look like bellow.
public interface IProductUtility
{
void SaveProductAcl<T>(Product product, T model);
}
The concrete class
public class ProductUtility : IProductUtility
{
private readonly IAclService _aclService;
private readonly ICustomerService _customerService;
public ProductUtility(IAclService aclService, ICustomerService customerService)
{
_aclService = aclService;
_customerService = customerService;
}
public void SaveProductAcl<T>(Product product, T model)
{
var mod = model as IProductViewModel;
product.SubjectToAcl = mod.SelectedCustomerRoleIds.Any();
var existingAclRecords = _aclService.GetAclRecords(product);
var allCustomerRoles = _customerService.GetAllCustomerRoles(true);
foreach (var customerRole in allCustomerRoles)
{
if (mod.SelectedCustomerRoleIds.Contains(customerRole.Id))
{
//new role
if (existingAclRecords.Count(acl => acl.CustomerRoleId == customerRole.Id) == 0)
_aclService.InsertAclRecord(product, customerRole.Id);
}
else
{
//remove role
var aclRecordToDelete = existingAclRecords.FirstOrDefault(acl => acl.CustomerRoleId == customerRole.Id);
if (aclRecordToDelete != null)
_aclService.DeleteAclRecord(aclRecordToDelete);
}
}
}
}
The IOC
builder.RegisterType<ProductUtility>().As<IProductUtility>()
.InstancePerLifetimeScope();
The IProductViewModel interface only one property for test
public interface IProductViewModel
{
IList<int> SelectedCustomerRoleIds { get; set; }
}
And the ViewModel of the Product at admin site.
public partial class ProductModel : BaseNopEntityModel, ILocalizedModel<ProductLocalizedModel>, IProductViewModel
{
.............
..............
................
public IList<int> SelectedCustomerRoleIds { get; set; }
}