首页 > 解决方案 > 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; }
}

标签: asp.net-mvcc#-4.0

解决方案


问题是您引用的是 Instance 而不是本地成员实例。

在本地成员前面放置下划线之类的内容通常是一种很好的做法,以使其更容易识别。

Instance 中的 getter 应如下所示:

            if (instance == null) instance = new ProductService();
            return instance;

我建议将其重命名为 _instance 以避免混淆。

高温高压

瓦兹德夫


推荐阅读