Showing posts with label ProjectBaseCore. Show all posts
Showing posts with label ProjectBaseCore. Show all posts

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;"
  }
}

Saturday, February 6, 2021

Injecting ProjectBaseCore in .Net Core Project

ProjectBaseCore (PBC) has to be injected to use in .net core project with version 2.x and later. After version 2.x, DatabaseFactory and QueryGeneratorFactory classes are no longer static classes. As a result, PBC version 2.x is not compatible with older versions, because you must inject DatabaseFactory and QueryGeneratorFactory classes or instantiate them with using new keyword.

First of all, in startup.js file or in a dependency injection container, injection must be defined:

services.AddSingleton<IDatabaseFactory, DatabaseFactory>();
services.AddSingleton<IQueryGeneratorFactory, QueryGeneratorFactory>();
In startup file, we write these codes in "ConfigureServices" function. After these declarations, we can use these services in controllers or middleware classes.

public class HomeController : Controller
{
     private readonly IDatabaseFactory _databaseFactory;
     private readonly IQueryGeneratorFactory _queryGeneratorFactory;

     public HomeController(IDatabaseFactory databaseFactory, IQueryGeneratorFactory queryGeneratorFactory)
     {
         _databaseFactory = databaseFactory;
         _queryGeneratorFactory = queryGeneratorFactory;
     }

     public IActionResult Index()
     {
         var db = _databaseFactory.GetDbObject();
         var qg = _queryGeneratorFactory.GetDbObject();
         qg.SelectText = "select * from product";

         var dt = db.ExecuteQueryDataTable(qg.GetSelectCommandBasic());
         return View();
     }
}