0

I'm trying to create only one instance over all my projects in solution. I want top prevent multiple database objects.

I have this organisation on project:

|-Solution:
|--- Core 
|-------- Common
|------------ App.cs <singleton>
|------------ Model.cs
|------------ Database.cs
|
|--- Project 1
|-------- Models
|------------- Users.cs
|------------- Products.cs
|------------- Categories.cs
|-------- UI
|-------- etc...
|
|--- Project 2
|--- Project 3
|--- Project 4

Core project is library project which has App singleton class, Model class is base class for models and database class for MySql.

Base Model:

namespace Core.Common
{
    public class Model : Database
    {
        public Database db;

        public Model()
        {
            db = new Database();

            if(db.IsConnected())
            {
                App.IsConnected = true;
            }
        }
    }
}

And in all my models i create this:

namespace Core.Models
{
    public class Products: Model
    {

        public Products() : base()
        {
            //..etc  
        }


        public DataTable ShowAll()
        {
            return db.query("SELECT * FROM products");
        }
    }
}

So all my project has models for database and model must extend base model class wich already contain database object for connecting. But all models class must extend base construcotr for establishing connection.

But am thinking this is litle bad practice.

What about to create object for database inside Main()? than will be globaly over priject right ?

Any other approach to improve this project?

Ivan
  • 5,139
  • 11
  • 53
  • 86
  • yeah it looks bad. use DI through method parameter instead of creating for every model. – Sushil Mate Jul 09 '16 at 10:11
  • hm in all my model methods to inject Database class is better right – Ivan Jul 09 '16 at 10:12
  • i would recommend using unity here. here is the link http://stackoverflow.com/a/608617/2745294 – Sushil Mate Jul 09 '16 at 10:17
  • all you want to access database through multiple models right. better to use unity & may be create in main method. try this one IOC approach http://stackoverflow.com/a/1532254/2745294 – Sushil Mate Jul 09 '16 at 10:21
  • So Di in constructor is best – Ivan Jul 09 '16 at 10:22
  • 1
    ivan, for starters lets try DI approch through constructor.. DI or IOC both has pros n cons. – Sushil Mate Jul 09 '16 at 10:27
  • But what when i create new object for `Product` model so i must assign database object `new Product(new Database)... I must learn more about container. Thanks for answers guys – Ivan Jul 09 '16 at 10:36
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/116865/discussion-between-sushil-mate-and-ivan). – Sushil Mate Jul 09 '16 at 10:52

0 Answers0