asp.net-mvc - com.services.dll 中发生了“System.StackOverflowException”类型的未处理异常
问题描述
我是初学者,正在学习 ASP.NET MVC,我的应用程序运行良好我已经了解了 Singleton,但是在我的应用程序中包含 Singleton 模式后,我在 com.service project.I 中的 ProductService 类上出现异常有一个解决方案,在那个解决方案中,我有 4 个项目,这些项目的名称分别为 com.Entities、com.database、com.services、com.web
我尝试在工具 -> 选项 -> 使用托管代码中检查使用托管兼容性代码
com.service:在公共静态 ProductService 实例中获取异常
public class ProductService
{
public static ProductService Instance
{
get
{
if (Instance == null) instance = new ProductService();
return instance;
}
}
private static ProductService instance { get; set; }
private ProductService() {}
CContext context = new CContext();
public List<Product> GetProducts()
{
return context.Products.Include(x => x.Category).ToList();
}
}
com.web:控制器
[HttpGet]
public ActionResult Edit(int id)
{
var prod = ProductService.Instance.GetProduct(id);
UpdateProductViewModels editModel = new UpdateProductViewModels ();
editModel.ID = prod.ID;
editModel.Name = prod.Name;
editModel.CategoryID = prod.Category != null ? prod.Category.ID : 0;
editModel.CategoryList = CategoryService.Instance.GetCategories();
return PartialView(editModel);
}
com.Entity
public class BaseEntity
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool isFeatured { get; set; }
public string ImageURL { get; set; }
}
命名空间 com.Entity
public class Product : BaseEntity
{
public decimal Price { get; set; }
public int CategoryID { get; set; }
public Category Category { get; set; }
}
解决方案
问题是您引用的是 Instance 而不是本地成员实例。
在本地成员前面放置下划线之类的内容通常是一种很好的做法,以使其更容易识别。
Instance 中的 getter 应如下所示:
if (instance == null) instance = new ProductService();
return instance;
我建议将其重命名为 _instance 以避免混淆。
高温高压
瓦兹德夫
推荐阅读
- python - 进行分布式训练时,torch.load 出错
- ios - Xcode 不会在项目中打开 swift 文件,文件图标是灰色的(低 alpha),从远程下载克隆后
- jquery - 在页脚之前使固定位置 Div 停止
- java - 使用 JAVA 从 .csv 文件中删除项目
- android - 关于图像随机的问题
- c# - 我是否在结构比较中使用 IEquatable Equals()?
- xcode - 错误:统一到xcode;架构 arm64 的未定义符号:
- google-apps-script - 如何通过应用程序脚本从谷歌表中获取特定范围的行数据
- firebase - 存储达到一定限制时触发firebase云功能
- c# - 从 Azure 表存储中检索记录抛出未设置对象引用