Extension Methods in .NET : How to Customize Internal C# Classes! My First Firefox Theme – Part 1
Dec 20

Network connections_64 Last week I was working in a solution for Database Versioning in C#. The first idea was to create a toll for PostGre and Mysql, but then I started to think: Why not create a toll which works for every database?

To make it possible I needed to use Dependency Injection so I decided to write this tutorial! : )

So first let’s understand the dependency injection:

Without the concept of dependency injection, a consumer who needs a particular service in order to accomplish a certain task would be responsible for handling the life-cycle (instantiating, opening and closing streams, disposing, etc.) of that service. Using the concept of dependency injection, however, the life-cycle of a service is handled by a dependency provider (typically a container) rather than the consumer. The consumer would thus only need a reference to an implementation of the service that it needed in order to accomplish the necessary task.

More here: http://en.wikipedia.org/wiki/Dependency_injection

Ok, that just doesn’t help a lot? Let’s code, so you can understand.

Image that we are building a class, and that class will be responsible to execute some commands in some random database. Let’s think about PostGre.

You have something like that:

Code Snippet
  1. class DatabaseWithoutDependencyInjection
  2. {
  3.  
  4.     NpgsqlConnection connection;
  5.  
  6.     public DatabaseWithoutDependencyInjection()
  7.     {
  8.  
  9.         connection = new NpgsqlConnection("Connection string");
  10.  
  11.         this.connection.Open();
  12.  
  13.     }
  14.  
  15.     public void executeCommand(string command)
  16.     {
  17.  
  18.         NpgsqlCommand com = new NpgsqlCommand(command);
  19.  
  20.         com.ExecuteNonQuery();
  21.  
  22.     }
  23.  
  24. }

 

Ok. Looking at our class you should see that was created a new connection in our constructor and that class created a NpgsqlConnection which is the PostGre connection, right? Obviously that class will work just for postgre, but now imagine if you can make it works for every kind of database in the world;

For that, we will need to insert the database injection.

Look at our constructor, it directly depends on the NpgsqlConnection and that makes our class work just for PostGre. To insert the dependency injection, we work with interfaces which describes the methods in a more generic way. If you right click on the NpgsqlConnection and “Go to definition” you will see that our connection implements the interface DbConnection, and if you go and check every database connection, it will implement the same interface.

Ok, now we know that all kind of database connections implements the DbConnection interface. What about we receive in our constructor that DbConnection? We just know that every kind a connection implements the DbConnection so we can do that.

Our constructor should be something like that now:

Code Snippet
  1. DbConnection connection;
  2.  
  3. public DatabaseWithoutDependencyInjection(DbConnection connection)
  4. {
  5.  
  6.     this.connection = connection;
  7.  
  8. }

 

Now we are receiving the DbConnection interface in our constructor… so we can pass every kind of connection to this class.

Our constructor is already under dependency injection, we are not connected to the NpgsqlConnection type in the constructor, now we receive a interface like parameter and that interface can be any database : )

Now we need to make our executeCommand method generic too, so we can send commands to any databases.

Let’s change our method to something like that:

Code Snippet
  1. public void executeCommand(string command)
  2. {
  3.  
  4.     DbCommand com = connection.CreateCommand();
  5.     com.CommandText = command;
  6.     com.ExecuteNonQuery();
  7.  
  8. }

 

We’ve just created an object which implements the DbCommand interface and execute the command, like the connection, that command should work for any database :)

Now to use this is simple, we just pass our connection like a parameter:

For postgre:

Code Snippet
  1. NpgsqlConnection conPgsql = new NpgsqlConnection("connection string");
  2.  
  3. DatabaseWithoutDependencyInjection database = new DatabaseWithoutDependencyInjection(conPgsql);
  4.  
  5. database.executeCommand("Random command");

 

For mysql:

Code Snippet
  1. MySqlConnection conMysql = new MySqlConnection("connection string");
  2.  
  3. DatabaseWithoutDependencyInjection database = new DatabaseWithoutDependencyInjection(conMysql);
  4.  
  5. database.executeCommand("Random command");

 

And the same time for any database :)

So that’s it. Dependency injection is a great pattern and helps a lot in huge applications.

Hope you enjoy the tutorial, share the link if you like :)

If you prefer, let your comments below or follow me in your social networks using the right bar!

Cya

  • Share/Bookmark

14 Responses to “Dependency Injection using .NET!”

  1. Gentil says:

    That’s really useful. I’ve done sth like that using Java, but never programming in .NET. Thanks a lot :)

  2. Мастер says:

    Интересует размещение рекламы на этом блоге.

  3. blog says:

    “Работай с умом, а не до ночи”

  4. Когда снега укроют землю, И Рождество наступит вновь, Бокал за счастье поднимите, За мир, за дружбу, за любовь! И чтоб без горя и сомнений Прожить Вам много светлых дней! Сберечь уют, покой семейный И уважение друзей! с рождеством вас! многоувожаемые и пусть новый год будет удачным и счастливым!

  5. Повар says:

    Класс! Афтару респект!

  6. ммм)) так клёво))

  7. Здраствуйте, не знаю куда писать напишу сюда. Я подписался на рсс вашего сайта, а текст отображается иероглифами помогите пожалуйста, можно на e-mail

  8. Меди says:

    а как сложно вести свой собственный блог?

  9. Action says:

    Скажите, а у вас есть RSS поток в этом блоге?

  10. Ценные рекомендации, беру на заметку

  11. забрала в цитатник, спасибо!

  12. Ваш сайт в опере не очень то корректо показывается, а так все отлично! спасибки вам за умные мысли!

  13. Да, всё точно написано.

  14. Лекарь says:

    Большое спасибо! Есть ещё повод получить удовольствие… С вашего разрешения, беру.

Leave a Reply

preload preload preload