user2195741
user2195741

Reputation:

StackOverFlow exception in getter

I'm using the Singleton design pattern and I must return the object if it hasn't been used before. I get an exception in the following code :

namespace app.Models
{
    public class Conexion:DbContext
    {    
        private static Conexion Instance = null;
        private Conexion(string con) : base(con) { }
        public static Conexion MainConexion 
        {
            get {//error here
                if (Instance == null)
                {
                    Instance = new Conexion(@"Server=*****; User Id=***;Password=****; Database=****");
                }
                return Instance;
            }
        }
        public DbSet<label> Labels { get; set; }
        public DbSet<checke_status> CheckStatus { get; set; }

        public void SaveChanges()
        {
            MainConexion.SaveChanges();
        }
    }
}

How can I solve this?

Upvotes: 0

Views: 151

Answers (1)

Dan
Dan

Reputation: 9847

Remove the override of the SaveChanges method:

namespace app.Models
{
    public class Conexion : DbContext
    {
        private static Conexion Instance = null;

        private Conexion(string con) : base(con) { }

        public static Conexion MainConexion 
        {
            get
            { //error here
                if (Instance == null)
                {
                    Instance = new Conexion(
                        @"Server=*****; User Id=***;Password=****; Database=****");
                }

                return Instance;
            }
        }

        public DbSet<label> Labels { get; set; }

        public DbSet<checke_status> CheckStatus { get; set; }
    }
}

Since you have a private constructor, the only instance of this class that can be used is the one exposed in the MainConexion property. It looks like you were trying to make sure that when any instance's SaveChanges method was called that the SaveChanges method on the MainConnection property's instance was called. This is not necessary, because you can only ever have one instance of the Conexion class, and it's the instance that you want to call SaveChanges on. The usage is still the same:

Conexion.MainConexion.SaveChanges();

That being said, I think you would have better luck if you were to not implement it this way. It would probably be better to open and close connections as they were needed, rather than rely on a single connection instance. What happens if the connection is interrupted? Rather than getting a single error, your application will be broken.

Upvotes: 2

Related Questions