我有一个asp.net mvc控制器,它在执行时调用服务类中的方法来打开文件并开始将记录导入数据库。我想以某种方式限制此方法或类,以便无法创建另一个实例,并阻止在完成运行之前再次调用该方法。我已经阅读过单例模式,但我不确定它是否可以实现,因为该类是通过依赖注入实例化的。
依赖注入由Autofac处理
服务类:
namespace Nop.Plugin.Misc.CAImport.Services
{
public class CAImportService: ICAImportService
{
#region Fields
private IProductService _productService;
private ICategoryService _categoryService;
private IManufacturerService _manufacturerService;
#endregion
#region Constructor
public CAImportService(IProductService productService,
ICategoryService categoryService,
IManufacturerService manufacturerService)
{
this._productService = productService;
this._categoryService = categoryService;
this._manufacturerService = manufacturerService;
}
#endregion
#region Methods
/// <summary>
/// Import products from tab delimited file
/// </summary>
/// <param name="fileName">String</param>
public virtual void ImportProducts(string fileName, bool deleteProducts)
{
//Do stuff to import products
}
#endregion
}
}
控制器类:
namespace Nop.Plugin.Misc.CAImport.Controllers
{
public class MiscCAImportController: BasePluginController
{
private ICAImportService _caImportService;
public MiscCAImportController(ICAImportService caImportService)
{
this._caImportService = caImportService;
}
[AdminAuthorize]
public ActionResult ImportProducts()
{
return View("~/plugins/misc.caimport/views/misccaimport/ImportProducts.cshtml");
}
[HttpPost]
[AdminAuthorize]
public ActionResult ImportProducts(ImportProductsModel model)
{
string fileName = Server.MapPath(model.Location);
_caImportService.ImportProducts(fileName, model.DeleteProducts);
return View("~/plugins/misc.caimport/views/misccaimport/ImportProducts.cshtml", model);
}
}
}
答案 0 :(得分:1)
下面的代码为您的服务添加了一个锁,以防止其他线程同时执行所附的语句。
public class CAImportService: ICAImportService
{
// OTHER METHODS AND SECTIONS REMOVED FOR CLARITY
// Define static object for the lock
public static readonly object _lock = new object();
/// <summary>
/// Import products from tab delimited file
/// </summary>
/// <param name="fileName">String</param>
public virtual void ImportProducts(string fileName, bool deleteProducts)
{
lock (_lock)
{
//Do stuff to import products
}
}
}