{"id":8425,"date":"2017-08-28T09:00:28","date_gmt":"2017-08-28T16:00:28","guid":{"rendered":"https:\/\/blogs.msdn.microsoft.com\/vbteam\/?p=8425"},"modified":"2024-07-05T12:36:22","modified_gmt":"2024-07-05T19:36:22","slug":"dependency-injection-with-visual-basic-net-part-1","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/vbteam\/dependency-injection-with-visual-basic-net-part-1\/","title":{"rendered":"Dependency Injection with Visual Basic .NET &#8211; Part 1"},"content":{"rendered":"<p><em>This post was authored by guest blogger Andr\u00e9 Obelink, a Visual Basic MVP, and published by the VBTeam on his behalf.<\/em>\nIn this first blog post of a series of two, I explain what dependency injection (DI) is and why you might want to use this design principle in your software. The target audience of this post is the junior \/ medium experienced software developer, with no knowledge of dependency injection or related techniques. In the second post, I\u2019ll describe the use of Inversion of Control Containers (IoC containers), to use dependency injection in a much more flexible way.<\/p>\n<h2>What is dependency injection?<\/h2>\n<p>Dependency injection isn\u2019t new. It\u2019s been around since the early 90s. Because it\u2019s a design principle, it isn\u2019t directly related to a specific programming language. For example, you can use this principle in Java, C#, or Visual Basic .NET. It\u2019s one of the <span><a href=\"https:\/\/en.wikipedia.org\/wiki\/SOLID_(object-oriented_design)\">principles of SOLID<\/a><\/span>. SOLID is a mnemonic acronym for the five basic principles of object-oriented programming and design. In my daily life as a software developer, I try to commit myself to apply the principles of SOLID. They were, years ago, defined by Robert C. Martin (also known as \u2018Uncle Bob\u2019). He\u2019s the author of many books, including \u2018Clean Code\u2019. A highly recommended book!\nLet\u2019s start from the beginning by defining the term \u2018dependency injection\u2019. However, this is easier said than done. Wikipedia says: \u201c<em>In software engineering, dependency injection is a technique whereby one object supplies the dependencies of another object. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. The service is made part of the client&#8217;s state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern<\/em>.\u201d\nIf you\u2019re new to this subject, you may read this definition more than once and still have no clue what exactly is meant. I think an example from real life might help.\nWhen you were a child, and you asked your mother to give you something to drink, you were happy when she handed you a cup of milk, a glass of orange juice, or a bottle of apple juice, for example. Your mother was in charge. You asked for a drink, but you didn\u2019t know what you\u2019d eventually get. The fact that you knew that you\u2019d get some drink, without knowing exactly which drink it would be, describes more-or-less the core concept of dependency injection. You don\u2019t know the exact type you\u2019ll get, but you know about, for example, the methods on the interface.\nLet\u2019s look at another example from daily life, more related to computer software. Perhaps you\u2019re familiar with Adobe Photoshop and their mechanism of plug-ins. You want to apply a filter to a photo. You can install a filter or plug-in, published by a third-party vendor. Adobe Photoshop doesn\u2019t know anything about that filter. However, when this plug-in is installed, it can execute the filter logic, and apply that specific implementation of the filter to the active photo. Again, there\u2019s a concept of not knowing about the filter that is installed, and the ability to apply that \u2018unknown\u2019 filter.\nIn my daily life as a developer, I use dependency injection a lot. Imagine, for example, the logging components we\u2019re using in our software, like Log4net. Based on configuration, it logs to different &#8211; or a combination of &#8211; output destinations. In our code, we call something general like _logger.Log(\u201cHello!\u201d). But when writing that code, we don\u2019t know where this text will end up. Is it in a text file or is logged to the Windows Event log? Or both? Or will an email be sent containing the message?<\/p>\n<h2>Four roles<\/h2>\n<p>It\u2019s important to understand that dependency injection involves four roles:<\/p>\n<ul>\n<li>The <strong>service<\/strong> <strong>objects<\/strong> to be used.<\/li>\n<li>The <strong>client<\/strong> <strong>object<\/strong> that is depending on the services it uses.<\/li>\n<li>The <strong>interfaces<\/strong> that define how the client may use the services.<\/li>\n<li>The <strong>injector<\/strong>, which is responsible for constructing the services and injecting them into the client.<\/li>\n<\/ul>\n<p>The <strong>service<\/strong> <strong>objects<\/strong> are the actual implementations of the logic you want to execute. In the example of the child asking for a drink, there are three \u2018DrinkServices\u2019: the <em>MilkDrinkService<\/em>, the <em>OrangeJuiceDrinkService,<\/em> and the <em>AppleJuiceDrinkService<\/em>.\nThe <em>Child<\/em> is the <strong>client object<\/strong>. It calls the <em>Drink()<\/em> method in one of the services. You can ask yourself the question: \u201cHow does the Child know that it can call something like a <em>Drink()<\/em> method?\u201d As you perhaps know, the <em>Child<\/em> is not aware \u2013 and not allowed to be aware &#8211; of the <em>MilkDrinkService<\/em> or one of the other services.\nThe <em>Child<\/em> knows about the <em>Drink()<\/em> method, because it calls a method on an <strong>interface<\/strong>, in our example the <em>IDrinkService<\/em>. An <strong><a href=\"https:\/\/docs.microsoft.com\/dotnet\/visual-basic\/programming-guide\/language-features\/interfaces\/\">interface<\/a><\/strong> defines the public members, but doesn\u2019t implement them. See it as a contract or a description of the signature of the class. A <strong>service object,<\/strong> which implements an interface, contains the actual logic.\nYou can compare the mother of the child with the <strong>injector<\/strong>. She\u2019s responsible for what kind of drink her child gets. The <strong>injector<\/strong> injects the actual logic.<\/p>\n<h2>Do some coding<\/h2>\n<p>I think that some code will clarify this abstract theory much better. It\u2019s a best practice to start with defining the <strong>interface. <\/strong>In this case, the <em>IDrinkService<\/em>.<\/p>\n<p>As you can see, it only defines which public methods are available. Because it always defines the public members, you must omit the keyword <em>Public<\/em>. And as I said earlier, it doesn\u2019t contain any implementation.\nThe <strong>service objects<\/strong> implement the logic of the interface. The <em>MilkDrinkService() <\/em>implements <em>IDrinkService<\/em>. In practice, this means that we will write the specific implementation of the <em>Drink()<\/em> method in this class.<\/p>\n<p>After you type \u2018Implements IDrinkService\u2019 and hits Enter, Visual Studio helps you by creating the method for you. Replace the \u2018Throw New NotImplementedException()\u2019 with the specific logic you want to execute in that service object. We have now implemented one of the service objects. The other two are quite similar. They differ only in the specific logic. Let\u2019s add the second service object.<\/p>\n<p>And the last service object isn\u2019t hard to guess:<\/p>\n<p>We now have coded all service objects. The next step is to define the <strong>client object<\/strong>. As you can remember, we must inject the service object into the consuming client object. There are a couple of ways to inject dependencies, but I\u2019m choosing to use \u2018constructor injection\u2019. Other techniques are, for example, \u2018setter injection\u2019 or \u2018interface injection\u2019. The first example is self-explanatory: the client object exposes a setter method that the injector uses to inject the dependency. The second example is harder to understand. Interface injection concludes that the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency. For now, forget these other two injection techniques and let\u2019s focus on constructor injection. In most cases, I use this type of injection because it always brings my client object in a valid state. To understand what I mean with this last statement, we should take a close look at the code.<\/p>\n<p>As you can notice, I added a constructor that forces to apply an argument of the type <em>IDrinkService<\/em>. This means that we can <em>only create<\/em> an instance of this object, when we provide an object that implements this interface. So, an instance of my client object has always the mandatory <em>_drinkService<\/em> set. When other developers use one of my DrinkServices, they\u2019re \u2018unable\u2019 to instantiate them in a wrong manner because Visual Studio is already telling them at design time that some mandatory information is missing (In comparison with setter injection, where this missing piece of code is only noticed when you\u2019re already running the code).\nNote that the client object has no references to &#8211; or knowledge of &#8211; our service objects. It\u2019s only aware of the methods of the interfaces that it implements.\nThe fourth step is creating the <strong>injector<\/strong>. The injector is responsible for defining and injecting the dependency, in our example on of our <em>DrinkServices<\/em>.<\/p>\n<p>You can imagine that the <em>Mother<\/em> class returns, based on some business logic or external configuration, one of the other services. The last part of our code example is using our classes.<\/p>\n<p>When executing this code, this results in the following output:\n<img decoding=\"async\" src=\"\" alt=\"\" width=\"500\" height=\"184\" class=\"size-mediumlarge wp-image-8445 alignnone\" \/>\nYou can play with this example by changing the implementation of the <em>Mother.GetDrinkService()<\/em> method. Our client object isn\u2019t aware of the actual services. And if you decide tomorrow to create a <em>BeerDrinkService()<\/em> method that implements the <em>IDrinkService<\/em> interface, all depending code will still run fine.<\/p>\n<h2>Why using dependency injection?<\/h2>\n<p>The concept of dependency injection introduces some abstraction to your business logic. Some developers experience this as adding extra complexity to the code base. Other developers, including myself, think that it just removes complexity. For me, the main reason to apply these design principles is that it makes my code more loosely coupled. Loosely coupling helps you make your code better maintainable, extensible, and testable. It helps your applications to get more configurable: you can even change logic without recompiling.\nBy applying dependency injection, you will find that your classes contain in most cases only one responsibility and that\u2019s a good thing. Single responsibility is one of the other five principles of SOLID. Indeed, you need dependency injection for a couple of other techniques defined by SOLID. I\u2019m convinced that applying these techniques helps you write better software.\nWhen writing unit tests, you will love these techniques even more! Imagine you have business logic that calculates the total amount of an order. The order, including the order lines, is retrieved from the database by an <em>OrderRepository<\/em> that implements the <em>IOrderRepository.GetOrderByNumber()<\/em> method. \u00a0When you want to write a unit test that calculates the total order amount, this code relies on data in the database. But this is not what you want, because when data in your database is changed, your unit test will fail. Also, when running this unit test as part of the automated build in, for example, the cloud service VSTS, it can\u2019t even connect with your database on premise.\nSo, to overcome this issue, when you want to unit test this piece code, the solution is to inject another service object that implements <em>IOrderRepository<\/em> too. For example, <em>FakeOrderRepository<\/em>. This fake or mock implementation will create an order and related lines in code. This code won\u2019t normally change and can be executed independent from a database. Your unit tests will be much more predictable.\nIn this post, I have explained the concept of Dependency Injection. By introducing interfaces and implement them with a concrete and specific logic, your code will be more flexible, easier to understand, to extend and to maintain.\nIn the next post, I\u2019ll show you the use of IoC containers, a technique that will help to assemble your application and other components by using dependency injection to a cohesive program.\nHappy coding!\n<strong>Andr\u00e9 Obelink<\/strong>\nTwitter: <a href=\"https:\/\/twitter.com\/obelink\">@obelink<\/a>\nBlog: <a href=\"https:\/\/www.obelink.com\/\">www.obelink.com<\/a>\n&nbsp;\nLinks:<\/p>\n<ul>\n<li><a href=\"https:\/\/github.com\/obelink\/DependencyInjectionVBPart01\">https:\/\/github.com\/obelink\/DependencyInjectionVBPart01<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>This post was authored by guest blogger Andr\u00e9 Obelink, a Visual Basic MVP, and published by the VBTeam on his behalf. In this first blog post of a series of two, I explain what dependency injection (DI) is and why you might want to use this design principle in your software. The target audience of [&hellip;]<\/p>\n","protected":false},"author":260,"featured_media":8818,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[19,195],"tags":[],"class_list":["post-8425","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-community-contribution","category-visual-basic"],"acf":[],"blog_post_summary":"<p>This post was authored by guest blogger Andr\u00e9 Obelink, a Visual Basic MVP, and published by the VBTeam on his behalf. In this first blog post of a series of two, I explain what dependency injection (DI) is and why you might want to use this design principle in your software. The target audience of [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/vbteam\/wp-json\/wp\/v2\/posts\/8425","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/vbteam\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/vbteam\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/vbteam\/wp-json\/wp\/v2\/users\/260"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/vbteam\/wp-json\/wp\/v2\/comments?post=8425"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/vbteam\/wp-json\/wp\/v2\/posts\/8425\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/vbteam\/wp-json\/wp\/v2\/media\/8818"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/vbteam\/wp-json\/wp\/v2\/media?parent=8425"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/vbteam\/wp-json\/wp\/v2\/categories?post=8425"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/vbteam\/wp-json\/wp\/v2\/tags?post=8425"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}