Tags: Dependency Injection

 

Dependency Injection Design Pattern Part 1  

 

Are you using dependency injections but you really don’t know how it works and what is the benefit of using DI?

Are you an old model of building software system with three tiers architecture? Where all tiers tightly coupled?

Are you data model centric architecture? Where the database and its schema is the center of the system?

 

Three tiers architecture and data model centric architecture approaches are still alive and sometimes could be wrong choice for your application.

If you are still using architecture such as this or if you don’t know the benefit of using DI then you have to read this blog about Dependency Injection as a design pattern.

So what is dependency injection? And why we need to use it?



You can download source code of the project from github

Here

 

The definition of the DI changed by the time, by looking into Wiki you will see that in 2006 this was the definition.

Dependency injection (DI) is a programming design pattern and architectural model, sometimes also referred to as Inversion of Control or IoC, although technically speaking, dependency injection specifically refers to an implementation of a particular form of IoC. The pattern seeks to establish a level of abstraction via a public interface, and to remove dependency on components by (for example) supplying a plug-in architecture. The architecture unites the components rather than the components linking themselves or being linked together. Dependency injection is a pattern in which responsibility for object creation and object linking is removed from the objects themselves and transferred to a factory. Dependency injection therefore is inverting the control for object creation and linking, and can be seen to be a form of IoC.



This definition has changed couples of times, and in 2018 the definition on wiki became as following:

In software engineering, dependency injection is a technique whereby one object (or static method) 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's state.[1] Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.

This fundamental requirement means that using values (services) produced within the class from new or static methods is prohibited. The client should accept values passed in from outside. This allows the client to make acquiring dependencies someone else's problem.

The intent behind dependency injection is to decouple objects to the extent that no client code has to be changed simply because an object it depends on needs to be changed to a different one.



But wait what does that mean!? , I am assuming that you still confused, to make things more easily in a nutshell and simple words, Dependency injection is a Design pattern that enables the developer to loosely coupled code.



But!! Why loosely coupled? , In this blog, you will see it is not that hard to add loosely coupled code to your applications by examples and step by step.

There are several benefits for using loosely coupled code

  1.   Extensibility (code that can response quickly for new requirement)

  2.   Testability ( you will be able to create unit testing )

  3.   Late binding

  4.   Parallel development (to speed up development no need to wait for others modules)

  5.   Maintainability (the maintenance process will be super easy in future)

From now on, you will start see these two terms loosely coupled and tightly coupling a lot

We will start by looking to an application that doesn’t use dependency application and see why the applications are suffering from tightly coupling, we will see some scenarios that should be easy to implement but are really hard without dependency injection.

 

DI Concepts:

DI has 5 types (patterns) as following:

  1.   Constructor Injection

  2.   Property Injection

  3.   Method Injection

  4.   Ambient Context

  5.   Service Locator

 

We will explain all of them but we will focus on constructor and property injection because those are most DI common used.

When we implement DI for our application most likely we will not do this manually, instead we will use native DI like Microsoft extension dependency injection or one of many DI containers and frameworks likes Unity, Ninject, Autofac and many others, But first we will do it manually so that we have good understanding how the DI working. From my experience, I note that if you are a developer using frameworks or new tools without even asking yourself how all the magic works have been done believe  me you are missing very great information that can help you to be more creative with solving problems.

 

Let’s start with our simple web MVC example without using DI J , this example could  be applied on any type of projects, like desktop application , web application or even mobile applications.

 

Let’s assume that we have a data analysis page that shows basic report showing students' attendance during the first semester, and the page will read this data from SQL database

I will create this project using features (modules) architecture and MVC areas, this is for a reason I will tell you why later on, our application interface will look like this

And our project architecture will look like this

This is a lot of work for this type of application, even if we have good application design it seems that we have separate layers, but in fact those layers are tightly coupled.

I will not explain the tiers architecture or Domain Driven Design in this blog because this is another story and it is needs a separate blog, so for now let’s draw simple diagram for our application

Presentations can’t provide it is feature without relying on the repository class , and the repository is a low class which interoperate with data store which for now is SQL , while the presentation is the high level domain object so in this particular case a high-level object depends on low level object, this how beginners build software traditionally, this is a high level view on a classic application with three tiers.

 

On the top we have a user page interface calls API of objects which implements business logic, objects which implements business logic call API of low-level  that interoperateswith data store layer in our case it is SQL database please note that this data store layer could be changed in any time to be CSV files or external third party API or different type of databases like noSql or any things else represent data store.

The controller references a concrete type of repository, so the controller takes responsibility for creating and managing reporting repository, Based on this we see that there is tightly coupled between controller and repository (StudentReports)

But wait things getting worse.

The repository references a concrete type of data store layer (FakeDB) , so the repository takes responsibility for creating and managing the service or data store layer.

This does not seem that bad especially for small application like this, but for much large application this could be a nightmare, what if for client change the data store to be Mysql or noSql or even CSV file, how we can add this for our application?

 

Most of the developers will use switch case to solve this issue, they will add key value to the  configuration file and based on that key they will create the new object

This is not the optimal solution for this case, because StudentReport class should not be responsible of checking and creating data store object also what if you want to cache CSV file, code will get more complicated, also how you will be able to create unit test for this?

 

The responsibility of the StudentReport is to get the report data, do some mapping, it should not select which data store to use, we should not need to change our Business logic if we want to add a different data store,

Our application got more complicated because we avoided SOLID principles

 

So what is the solution? Loose coupling will help us resolve this issue.

 

You may be wondering why this solution has a lot of layers and the application like it has good design architecture, believe me I meet a lot of people their job title architect that they think Organize classes into folders and layers is a good architecture for the application and I was thinking this true for long time , but this totally wrong, if you are not using the right design pattern in right cases you are not adding any real useful values for your application

 

  • Accessing Different Data Stores

we can solve this problem by introducing an extra level of indirection, First we need to create common interface for repository (IFakeDBREpository) that allow us to plug any type of repository that implement this interface

This seems to allow us to inject any dependency we want which of course implements that interface, this is a simple powerful technique to invert dependencies achieving low coupling between components.

 

Now that we have the interface we will start to break our tight coupling By Inject the repository in the constructor

 

The most beneficial aspect of constructor injection is that it protects the invariants of the object. The object once created will always be in a valid state.

 

Interface repository: This means that this field is not tight to specific concrete class we can assign any class implement this interface

 

We need to make the injection someone else problem and our class is not responsible of creating the concrete type of the repository.

 

Now our class only cares about the interface but not of any particular concrete type, so the StudentReports class accepts any class implementing IFakeDBRepositroy.

 

 

Now we can add repositories as much as we need, and create the repository type that you want.

In the controller we are choosing a Sql repository, and we can create the repository type that we want.

Now go and publish the project and see the result

Ok good let’s change the repository to CSV and see the result again

 

So far so good, it's working fine we got different results.

 

But wait a minute we still have tight coupling in our controller, our controller should not be responsible for creating data store object, it should be responsible for preparing view Model object and pass it to view, so far we have done the removing of tight coupling manually, but will see that the DI (dependency injection) container gives us some really important functionality and simplicity our code.

 

DI Container can do much more for us a really big feature is life time management

 

  •   Singleton

  •   Transient

  •   Scope

Two ways of dealing with Dependency injection

 

1)   Custom DI builds your own.

2)   Use an IoC-Container(also known as DI-Containers) , which is a framework helps to apply DI and has many features

 

Before we start using one of the DI Containers framework, for more understanding let’s build simple DI and see how it works.

 

let's convert creating new object to Native DI container EX: new StudentsReports(new CsvDb()) , simply we need two methods Register class and Resolve class in other words we need to register the StudentsReports  , CsvDb  class and resolve them when needed.

 

 

Ioc-Container recursively creates all the required dependencies, imagine that we make a call to an Ioc-Container to resolve the StudentsReports, in other words we want from Ioc-container to get an instance of the StudentsReports class the IoC will look further to find how to resolve it , in our case StudentsReports takes interface in the constructor so the container will try to create the CsvDb in order to create the StudentsReports class the container has to pass to its constructor the CsvDb repository since the StudentsReports class depends on this interface to resolve the CsvDb repository , so this is how our containers are recursively resolved dependencies.

 

Let’s build IContainer interface that has Register and Resolver methods

Now let’s create SimpleID that implements the IContainer

This map will contain one to one relationships between dependences

This is generic method which takes two types and adds them to our map

The T parameter is the type which the client wants to be resolved and this method calls another private method that implements all the logic.

Here we get the corresponding type from the map; if we didn’t find it we throw an exception.

By using the reflection we can get request constructors , for simplicity let's get the first one and request it's parameters, if there is no parameters we just create an instance of the dependency and return it, otherwise we need to resolve them recursively, this is very simple Ioc-container you will find a lot of examples on the internet.

Simply we need to register StudentsReports and CsvDb that implementing IFakeDBErpository , let's debug the program to ensure that everything works fine.

Great it works fine and we resolved the dependencies properly.

 

In DI part 2 blog i will take you to next level, and i will be talking about

  •   parameterless constructor

  •   constructor overloading

  •   how we can inject our class directlly to controller constructor

  •   we will add new implementaion to our simple DI in order to support multi repository injection

  •   i will show you how we can integerate our simple IoC with asp.net resolver

 

If you found this blog useful , please share it with others , if not please add your thoughts.

43 Comments

  • Michael

    6 years ago

    Great post !

  • Hello World! https://locr7a.com?hs=eaa079be7a009d6a331be1a7a0fe9c20&

    23 months ago

    krpg75

  • Anaelay

    20 months ago

    8 Early work on developing daptomycin was abandoned due to observed myopathy but was resumed in 1997 when Cubist Pharmaceuticals Inc <a href=http://buycialis.homes>best price cialis</a> I got pregnant again a few months later

  • rfqcgwszzz

    19 months ago

    Gap
    rfqcgwszzz http://www.gd6f47p61161n9956jkd38zniz6oehd5s.org/
    <a href="http://www.gd6f47p61161n9956jkd38zniz6oehd5s.org/">arfqcgwszzz</a>
    [url=http://www.gd6f47p61161n9956jkd38zniz6oehd5s.org/]urfqcgwszzz[/url]

  • bmipgjsemo

    19 months ago

    Gap
    [url=http://www.gq7ga92p49t6o9o34766tf20j0wg4qijs.org/]ubmipgjsemo[/url]
    <a href="http://www.gq7ga92p49t6o9o34766tf20j0wg4qijs.org/">abmipgjsemo</a>
    bmipgjsemo http://www.gq7ga92p49t6o9o34766tf20j0wg4qijs.org/

  • cibezgvthr

    19 months ago

    Gap
    [url=http://www.g71fp4odj5rj90500rr78zw243bi5k8ss.org/]ucibezgvthr[/url]
    <a href="http://www.g71fp4odj5rj90500rr78zw243bi5k8ss.org/">acibezgvthr</a>
    cibezgvthr http://www.g71fp4odj5rj90500rr78zw243bi5k8ss.org/

  • yzhhjmctf

    19 months ago

    Gap
    <a href="http://www.gn6q1r2p270g7mq7437cdo1ol2hjn315s.org/">ayzhhjmctf</a>
    [url=http://www.gn6q1r2p270g7mq7437cdo1ol2hjn315s.org/]uyzhhjmctf[/url]
    yzhhjmctf http://www.gn6q1r2p270g7mq7437cdo1ol2hjn315s.org/

  • EdwinGoory

    19 months ago

    ChatCrypto is building a high performance AI Bot which is CHATGPT of CRYPTO.
    We are launching the Worlds first deflationary Artificial Intelligence token (CHATCRYPTOTOKEN) which will be used as a payment gateway to license
    Be rest assured and happy to be part of Chatcrypto family as signing up would give you free 1600 chatcrypto tokens(CCAIT)
    Project link https://bit.ly/41Fp0jc
    and with every referral you refer to Chatcrypto, you earn extra 1600 tokens for free.
    q1w2e19z

  • Hello World! https://racetrack.top/go/hezwgobsmq5dinbw?hs=eaa079be7a009d6a331be1a7a0fe9c20&

    19 months ago

    80kwc8

  • ybiwzzsvlm

    18 months ago

    Gap
    [url=http://www.g5o9m87pv2yngb04np4h9h742re50m08s.org/]uybiwzzsvlm[/url]
    ybiwzzsvlm http://www.g5o9m87pv2yngb04np4h9h742re50m08s.org/
    <a href="http://www.g5o9m87pv2yngb04np4h9h742re50m08s.org/">aybiwzzsvlm</a>

  • AndreTum

    18 months ago

    Peer2Profit lets you earn money by giving away your unused Internet connection! Share your WiFi or mobile connection and get paid for every gigabyte of traffic. To start earning, simply create a free account on our website and sign in to the app.
    SHARE YOUR TRAFFIC AND PROFIT ON IT! website link Peer2Profit http://bit.ly/3GwuVPK
    Withdrawal works fine withdrawn more than once, the minimum withdrawal of $ 2
    q1w@e33z

  • prfmnxhpft

    18 months ago

    Gap
    [url=http://www.gp62s9yk49q6b8170mp9q0k2g8u8iu9hs.org/]uprfmnxhpft[/url]
    <a href="http://www.gp62s9yk49q6b8170mp9q0k2g8u8iu9hs.org/">aprfmnxhpft</a>
    prfmnxhpft http://www.gp62s9yk49q6b8170mp9q0k2g8u8iu9hs.org/

  • Dont click me: https://racetrack.top/go/hezwgobsmq5dinbw?hs=eaa079be7a009d6a331be1a7a0fe9c20&

    18 months ago

    2tqx19

  • xjdowytxkz

    18 months ago

    Gap
    <a href="http://www.g9lw5o7du268304be329ypgdlfw8078ls.org/">axjdowytxkz</a>
    xjdowytxkz http://www.g9lw5o7du268304be329ypgdlfw8078ls.org/
    [url=http://www.g9lw5o7du268304be329ypgdlfw8078ls.org/]uxjdowytxkz[/url]

  • Billytrene

    17 months ago

    State of the art robot that automatically claims faucets and collects them into your own wallets.
    We have selected only the best - direct paying - faucets that are currently on the market. It is fully automated, no need to manually enter the CAPTCHAs.
    Highly customizable, easy to use and powerful Faucet Collector Bot.
    https://drive.google.com/file/d/1I8kuutG0vYstYumVs5K-d2SObesyMu9u/view

    @"1"@

  • 🌍 Hello World! https://national-team.top/go/hezwgobsmq5dinbw?hs=eaa079be7a009d6a331be1a7a0fe9c20 🌍

    16 months ago

    w54bpi

  • grtfidmpm

    15 months ago

    Gap
    grtfidmpm http://www.g87cp9f3614h0w90134avo8xds8wp6rrs.org/
    <a href="http://www.g87cp9f3614h0w90134avo8xds8wp6rrs.org/">agrtfidmpm</a>
    [url=http://www.g87cp9f3614h0w90134avo8xds8wp6rrs.org/]ugrtfidmpm[/url]

  • 35.01hw33x3b43t2nr9bwchef1nyt@mail4u.fun

    7 months ago

    natus cum rerum rerum enim quidem ad sequi tempora repellat et. error quia dolorem doloribus eius sit sit aut qui aut culpa ab ut. maxime rerum quisquam pariatur voluptas fuga ut voluptatem praesentiu

  • 36.01hw33x3b43t2nr9bwchef1nyt@mail5u.info

    7 months ago

    nihil quaerat qui incidunt ut excepturi quaerat rerum mollitia maiores laborum magni non. deleniti non cum vel laboriosam voluptas sequi eveniet dolorem voluptas sed. ducimus maiores accusamus rerum d

  • dzthbpprr

    4 months ago

    Gap
    <a href="http://www.g1o5wnys92j8bt1cj23p459gz10d0d12s.org/">adzthbpprr</a>
    [url=http://www.g1o5wnys92j8bt1cj23p459gz10d0d12s.org/]udzthbpprr[/url]
    dzthbpprr http://www.g1o5wnys92j8bt1cj23p459gz10d0d12s.org/

  • Jaredthurl

    2 months ago

    Стильные советы по подбору стильных луков на каждый день.
    Обзоры профессионалов, новости, все новинки и шоу.
    https://luxe-moda.ru/chic/499-10-maloizvestnyh-faktov-o-demne-gvasalii/

  • Charlesnap

    2 months ago

    Стильные советы по выбору стильных луков на любой день.
    Обзоры профессионалов, события, все коллекции и шоу.
    https://metamoda.ru/moda/1141-7-prichin-lyubit-dizaynera-rick-owens/

  • Charlessot

    2 months ago

    Модные советы по подбору отличных видов на каждый день.
    Статьи экспертов, новости, все дропы и мероприятия.
    https://lecoupon.ru/news/2024-09-26-5-samyh-udachnyh-modeley-krossovok-dolce-gabbana/

  • DavidIniny

    2 months ago

    Стильные советы по подбору отличных образов на каждый день.
    Мнения экспертов, новости, все показы и шоу.
    https://superlooks.ru/events/112-plein-sport-stilnaya-obuv-ot-philipp-plein/

  • DannyAvaws

    2 months ago

    Несомненно стильные события мира fashion.
    Актуальные новости мировых подуимов.
    Модные дома, торговые марки, haute couture.
    Новое место для модных людей.
    https://outstreet.ru/yeah/11164-5-stilnyh-modeley-chasov-guess-dlya-devushki-v-2024-godu/

  • JasonRib

    2 months ago

    Стильные советы по подбору превосходных луков на каждый день.
    Заметки профессионалов, события, все коллекции и шоу.
    https://luxe-moda.ru/chic/505-7-luchshih-sumok-guess-dlya-pokupki-v-2024-godu-stil-i-funktsionalnost/

  • Dexterkitle

    2 months ago

    Модные советы по подбору превосходных видов на каждый день.
    Статьи стилистов, события, все дропы и мероприятия.
    https://myfashionacademy.ru/material/2024-06-26-12-luchshih-brendov-krossovok-kotorye-stoit-kupit-pryamo-seychas/

  • BrianTwism

    2 months ago

    Стильные заметки по выбору превосходных видов на каждый день.
    Заметки экспертов, новости, все новинки и шоу.
    https://sneakersgo.ru/content/italyanskih-shik-dlya-vashih-glaz-opravy-ot-prada/

  • Michaeljouby

    2 months ago

    Стильные заметки по созданию отличных видов на каждый день.
    Статьи стилистов, события, все дропы и шоу.
    https://watches.superpodium.com/fashion/2804-7-reasons-to-love-patek-philippe-nautilus/

  • WillieCax

    2 months ago

    Модные советы по подбору модных луков на любой день.
    Мнения профессионалов, новости, все новые коллекции и мероприятия.
    https://luxe-moda.ru/chic/564-10-prichin-lyubit-brend-brunello-cucinelli/

  • Isaactub

    2 months ago

    Стильные заметки по созданию модных образов на каждый день.
    Обзоры экспертов, новости, все новые коллекции и шоу.
    https://lecoupon.ru/news/2029-10-02-7-prichin-lyubit-brend-herno/

  • ZacharyMeeNo

    2 months ago

    Модные заметки по выбору необычных видов на каждый день.
    Статьи стилистов, события, все показы и шоу.
    https://urban-moda.ru/all/749-za-chto-my-lyubim-brend-coach-ikona-amerikanskogo-stilya-i-masterstva/

  • Jameswrame

    2 months ago

    Модные советы по выбору превосходных образов на каждый день.
    Обзоры экспертов, события, все новые коллекции и мероприятия.
    https://sofiamoda.ru/style/2024-10-03-principe-di-bologna-roskosh-italyanskogo-stilya-i-elegantnost-na-kazhdyy-den/

  • ClintonIncug

    2 months ago

    Стильные заметки по созданию крутых луков на каждый день.
    Заметки экспертов, новости, все показы и мероприятия.
    https://watches.superpodium.com/

  • Jamesmut

    2 months ago

    The fashion house of Balenciaga has been a revolutionary force in the world of high fashion. Established by Spanish designer **Cristobal Balenciaga**, the brand rapidly grew into a symbol of modernity and high craftsmanship.
    Since its inception, Balenciaga redefined fashion standards with trendsetting designs. Cristobal Balenciaga was known for his sculptural silhouettes, designing garments that reshaped the way women dressed.
    Today, under the creative direction of **Demna Gvasalia**, Balenciaga continues to lead the luxury market, introducing avant-garde collections. Gvasalia’s style has taken the brand to new heights, highlighting a blend of high fashion and urban culture.
    The brand's collections often feature a fusion of art and fashion, pushing the boundaries of fashion. Balenciaga’s iconic pieces include the Hourglass bags, now stand as symbols of modern streetwear culture.
    In addition to its clothing lines, Balenciaga also produces a wide range of luxury accessories and footwear. The brand’s boutiques are located in leading cities worldwide, such as Paris, New York, and Tokyo.
    Whether it's through its cutting-edge designs, Balenciaga continues to be an iconic brand in the luxury fashion landscape, leading the evolution of couture.
    https://balenciaga.metamoda.ru/

  • Michaeldrini

    7 weeks ago

    На данном ресурсе вы можете найти брендовые сумки Bottega Veneta. Здесь можно приобрести актуальные модели, которые добавят элегантности вашему образу. Каждое изделие характеризуется превосходным исполнением, что свойственно бренду Боттега Венета
    https://bookmark-dofollow.com/story20868131/bottega-veneta

  • Elijahunemy

    7 weeks ago

    Bottega Veneta — это знаменитый итальянский бренд, известный неповторимым стилем. Основанный в 1966 году, бренд стал символом стиля и элегантности и славится кожаными изделиями высочайшего качества. Каждая вещь от Bottega Veneta передаёт традиции мастерства, а также уникальный подход к дизайну.
    https://bottega-official.ru

  • DavidHag

    7 weeks ago

    Бренд Tissot — известный Швейцарский производитель наручных устройств, что славится своим высочайшим качеством и стильным дизайном. Уже более столетия с половиной компания производит инновационные хронометры, что завоевали популярность по всему миру.
    https://tissot.icefashion.ru

  • Где купить Bottega Veneta

    7 weeks ago

    Наш интернет-магазин Боттега Венета предлагает разнообразие оригинальной продукции от знаменитого производителя. Здесь вы сможете выбрать и купить аксессуары последних поступлений с доставкой по Москве и России.
    https://bottega-official.ru

  • 🔗 You have received a email № 835. Read - https://telegra.ph/Go-to-your-personal-cabinet-08-25?hs=eaa079be7a009d6a331be1a7a0fe9c20& 🔗

    6 weeks ago

    k0w8sx

  • DanielDrera

    6 weeks ago

    В нашем магазине можно найти брендовые товары от бренда Gucci . Коллекция включает обувь и аксессуары , для самых изысканных покупателей.
    https://boutique.gucci1.ru

  • 📅 You have a transfer from user. Verify >> https://telegra.ph/Bitcoin-Transfer-12-04?hs=eaa079be7a009d6a331be1a7a0fe9c20& 📅

    11 days ago

    reuruz

  • 🔓 Email: Transaction #DW36. RECEIVE > https://telegra.ph/Ticket--9515-12-16?hs=eaa079be7a009d6a331be1a7a0fe9c20& 🔓

    4 days ago

    5gtpf1

Leave A Comment