Sunday, February 7, 2021

Using ProjectBaseCore without Dependency Injection

We can use ProjectBaseCore(PBC) without dependency injection(DI) by instantiating DatabaseFactory class with new keyword. We can give to factory class's constructor function a object that is implemented IConfiguration interface, or we can create database object by simply giving connection string and provider parameters to GetDbObject function. I give a console application example of how to use PBC without DI.

Program.cs:
class Program
{
   static void Main(string[] args)
   {
        DatabaseFactory databaseFactory = new DatabaseFactory(GetConfiguration());
        IDatabase2 db = databaseFactory.GetDbObject();
        var dt = db.ExecuteQueryDataTable("select * from product");
   }

   static IConfigurationRoot GetConfiguration()
   {
         var builder = new ConfigurationBuilder()
           .SetBasePath(System.AppContext.BaseDirectory)
           .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

         return builder.Build();
   }
}
appsettings.json:
{
  "DefaultDb": "Context",
  "ContextProviderName": "MySql.Data.MySqlClient",
  "ConnectionStrings": {
    "Context": "Server=localhost;Database=db;Uid=root;Pwd=1234;"
  }
}

No comments:

Post a Comment