1

I am trying to create a .Net core console application with can use different database connections. currently, i am writing the application to use SQL and in future if i want to use Oracle or any other connection then i should be able to easily achieve this. So, i am using dependency injection for this purpose.

I am exploring the below option using ServiceCollection

IConfiguration config = new ConfigurationBuilder()
                       .AddJsonFile("appsettings.json", true, true)
                       .Build();
var sqlconnectionstring = config.GetConnectionString("SQLConnectionString");
var serviceProvider = new ServiceCollection()
                       .AddLogging()
                       .AddSingleton<IChannel, Email>()
                       .AddTransient<IDBObjectManager>(s => new SQLDBObject(sqlconnectionstring))

Here the idea is, I have created a SQLDBObject class which will have SQL related functionalities. In future, I will create one for some other db.

I am seeing many articles around this with Entity Framework but at this point I am checking to make this functionality work with my SQL connection class.

I don't know if i am using the DI correctly here. Can someone advise?

  • 1
    check this answer: https://stackoverflow.com/a/43088581/261560 – Prashant Lakhlani Sep 28 '18 at 12:17
  • 1
    Sure, you can have an ADO.NET based repository system. Just code them to a common interface, and have their constructors depend on an object that describes how to connect to the database. Exactly like you've shown. I will suggest you use [Dapper](https://github.com/StackExchange/Dapper) within your repositories, as it takes out a lot of the boiler plate. – mason Sep 28 '18 at 12:25
  • Thank You Prashant and mason for your answers. I was not aware of the options pattern and the answer helped me in understanding better. Also, I will try to implement dapper and refine the code. Thanks again! – Karthick Trichy Chandrasekaran Oct 03 '18 at 06:46

0 Answers0