com.services.dll中发生类型为'System.StackOverflowException'的未处理异常

时间:2019-02-16 17:47:06

标签: asp.net-mvc c#-4.0

我是一个初学者,正在学习ASP.NET MVC,我的应用程序运行正常,我已经了解了Singleton,但是在应用程序中包含Singleton模式之后,我在com.service中的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.Entities

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.Entities

public class Product : BaseEntity
{
    public decimal Price { get; set; }
    public int CategoryID { get; set; }
    public Category Category { get; set; }
}

1 个答案:

答案 0 :(得分:0)

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

通常最好的做法是在本地成员的前面加上下划线,以使其更容易识别。

实例中的吸气剂应如下所示:

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

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

HTH

wazdev