Search code examples
c#sqliteobjectmdi

C# Multiple form application using same instance of object?


I have multiple forms that would need to communicate with database. I have an embedded database sqlite which requires only one dll file. Main form creates SQLite objects

using System.Data.SQLite;
...
public  SQLiteConnection sqlite_conn;
public  SQLiteCommand sqlite_cmd;
public  SQLiteDataReader sqlite_datareader;

which are initialized later in code. My question is , if I have multiple forms that need to communicate with database, is it better practice to give them using System.Data.SQLite and create their own instances of object or somehow use the same object from multiple forms, not at the same time...


Solution

  • Those classes aren't thread-safe, so you can't instantiate them once and share them between forms that are visible (or more precisely, access the database) at the same time.

    If you feel you're copying code all over the place, put that code in a class and parameterize it so you can inject an instance of that class into all forms that need it.

    Perhaps you can use Entity Framework, which helps deduplicate database code.