<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ dependency injection - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ dependency injection - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 21 May 2026 16:11:07 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/dependency-injection/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Implement Dependency Injection in FastAPI ]]>
                </title>
                <description>
                    <![CDATA[ Several languages and frameworks depend on dependency injection—no pun intended. Go, Angular, NestJS, and Python's FastAPI all use it as a core pattern. If you've been working with FastAPI, you've likely encountered dependencies in action. Perhaps yo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-implement-dependency-injection-in-fastapi/</link>
                <guid isPermaLink="false">691740a91f4fa448325a55f9</guid>
                
                    <category>
                        <![CDATA[ dependency injection ]]>
                    </category>
                
                    <category>
                        <![CDATA[ FastAPI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ backend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nneoma Uche ]]>
                </dc:creator>
                <pubDate>Fri, 14 Nov 2025 14:46:01 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1763131442081/76eff35b-be68-49c1-9743-d78ebc87b292.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Several languages and frameworks depend on dependency injection—no pun intended. Go, Angular, NestJS, and Python's FastAPI all use it as a core pattern.</p>
<p>If you've been working with FastAPI, you've likely encountered dependencies in action. Perhaps you saw <code>Depends()</code> in a tutorial or the docs and were confused for a minute. I certainly was. That confusion sparked weeks of experimenting with this system. The truth is, you can't avoid dependency injection when building backend services with FastAPI. It's baked into the framework's DNA, powering everything from authentication and database connections to request validation.</p>
<p>FastAPI's docs describe its dependency injection system as 'powerful but intuitive.' That’s accurate, once you understand how it works. This article breaks it down, covering function dependencies, class dependencies, dependency scopes, as well as practical examples.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-dependencies-and-dependency-injection-in-fastapi">Dependencies and Dependency Injection in FastAPI</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-getting-started-environment-setup">Getting Started: Environment Setup</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-types-of-dependencies-in-fastapi">Types of Dependencies in FastAPI</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-use-function-dependencies-in-fastapi">How to Use Function Dependencies in FastAPI</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-class-dependencies-in-fastapi">How to Use Class Dependencies in FastAPI</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-dependency-scope">Dependency Scope</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-path-operation-level">Path Operation Level</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-router-level">Router Level</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-application-level">Application Level</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-common-use-cases-for-dependency-injection">Common Use Cases for Dependency Injection</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along with this article, you should have:</p>
<ul>
<li><p>Working knowledge of Python.</p>
</li>
<li><p>Ability to create and activate virtual environments.</p>
</li>
<li><p>Basic understanding of FastAPI.</p>
</li>
<li><p>Familiarity with Object-Oriented Programming (OOP) concepts.</p>
</li>
</ul>
<h2 id="heading-dependencies-and-dependency-injection-in-fastapi">Dependencies and Dependency Injection in FastAPI</h2>
<p>A dependency is a reusable piece of logic, like authentication, database connection, or validation, that your path operations require. Dependency injection (DI) is how FastAPI delivers these dependencies to specific parts of your application: you declare them using <code>Depends()</code> and FastAPI automatically executes them when the associated route receives a request.</p>
<p>Think of it as requesting the tools your application needs. You declare dependencies once and FastAPI provides them wherever needed, with no repetitive setup across routes.</p>
<p>This makes for modular, scalable applications. Without DI, you would have to repeat the same setup code on every endpoint, making updates tedious and bugs more likely.</p>
<h2 id="heading-getting-started-environment-setup">Getting Started: Environment Setup</h2>
<p>Let's set up your development environment to work through the examples in this guide.</p>
<p>Start by creating a project folder, then:</p>
<p>Create and activate a virtual environment:</p>
<pre><code class="lang-bash">python -m venv deps
<span class="hljs-built_in">source</span> deps/bin/activate          <span class="hljs-comment">#on Mac</span>
deps\Scripts\activate             <span class="hljs-comment"># On Windows</span>
</code></pre>
<p>Install FastAPI with all dependencies:</p>
<pre><code class="lang-python">pip install <span class="hljs-string">'fastapi[all]'</span>
</code></pre>
<p>Organize your project as follows:</p>
<pre><code class="lang-python">fastapi-deps/
├── deps/                 <span class="hljs-comment"># Virtual environment</span>
├── function_deps.py
├── class_deps.py
├── router_deps.py
├── app.py
└── requirements.txt
</code></pre>
<h2 id="heading-types-of-dependencies-in-fastapi">Types of Dependencies in FastAPI</h2>
<p>In FastAPI, a dependency is a callable object that retrieves or verifies information before a route executes. Dependencies can be implemented as either functions or classes.</p>
<p><strong>Function dependencies</strong> are the most straightforward approach and work well for most use cases, including validation, authentication, and data retrieval. <strong>Class dependencies</strong> can handle the same tasks but are particularly useful when you need stateful logic, multiple instances with different configurations, or prefer object-oriented patterns.</p>
<h3 id="heading-how-to-use-function-dependencies-in-fastapi">How to Use Function Dependencies in FastAPI</h3>
<p>A function dependency is a helper function (such as for authentication or data retrieval) that can be injected into path operations. To demonstrate, we'll create a simple user authentication dependency using an in-memory database—a list of dictionaries.</p>
<p>Recall the folder structure from earlier? We’ll write this code in <code>fastapi-deps/function_deps.py</code>.</p>
<p>Start by importing the required modules:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> fastapi <span class="hljs-keyword">import</span> FastAPI, Depends, HTTPException
<span class="hljs-keyword">import</span> uvicorn
</code></pre>
<p>You bring in <code>FastAPI</code> to create the app instance, <code>Depends</code> for dependency injection, and <code>HTTPException</code> to handle errors gracefully. <code>uvicorn</code> will be used to run the application later.</p>
<p>Next, instantiate the FastAPI application:</p>
<pre><code class="lang-python">app = FastAPI()
</code></pre>
<p><code>app = FastAPI()</code> creates your application instance: the object that will hold all your endpoints and dependencies.</p>
<p>Next, create an in-memory database. Define a list of dictionaries to act as your temporary database. Each dictionary represents a user entry containing a name and a password.</p>
<pre><code class="lang-python">users = [
    {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Ore"</span>, <span class="hljs-string">"password"</span>: <span class="hljs-string">"jkzvdgwya12"</span>},
    {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Uche"</span>, <span class="hljs-string">"password"</span>: <span class="hljs-string">"lga546"</span>},
    {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Seke"</span>, <span class="hljs-string">"password"</span>: <span class="hljs-string">"SK99!"</span>},
    {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Afi"</span>, <span class="hljs-string">"password"</span>: <span class="hljs-string">"Afi@144"</span>},
    {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Sam"</span>, <span class="hljs-string">"password"</span>: <span class="hljs-string">"goTiger72*"</span>},
    {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Ozi"</span>, <span class="hljs-string">"password"</span>: <span class="hljs-string">"xx%hI"</span>},
    {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Ella"</span>, <span class="hljs-string">"password"</span>: <span class="hljs-string">"Opecluv18"</span>},
    {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Claire"</span>, <span class="hljs-string">"password"</span>: <span class="hljs-string">"cBoss@14G"</span>},
    {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Sena"</span>, <span class="hljs-string">"password"</span>: <span class="hljs-string">"SenDaBoss5"</span>},
    {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Ify"</span>, <span class="hljs-string">"password"</span>: <span class="hljs-string">"184Norab"</span>}  
]
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">This type of database isn’t persistent; any data stored therein is lost when the application restarts.</div>
</div>

<p>Then, define a dependency function for user validation. The simple helper function below checks whether a username and password provided by the user match an existing user in the database.</p>
<pre><code class="lang-python"><span class="hljs-comment">#the dependency function</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">user_dep</span>(<span class="hljs-params">name: str, password: str</span>):</span>
    <span class="hljs-keyword">for</span> u <span class="hljs-keyword">in</span> users:
        <span class="hljs-keyword">if</span> u[<span class="hljs-string">"name"</span>] == name <span class="hljs-keyword">and</span> u[<span class="hljs-string">"password"</span>] == password:
            <span class="hljs-keyword">return</span> {<span class="hljs-string">"name"</span>: name, <span class="hljs-string">"valid"</span>: <span class="hljs-literal">True</span>}
</code></pre>
<p>This function expects two string parameters, <code>name</code> and <code>password</code>, from the incoming request. If it finds a match in the <code>users</code> database, it returns a dictionary confirming the user’s validity. FastAPI automatically converts this dictionary into a JSON response.</p>
<p>Next, inject the dependency into a path function:</p>
<pre><code class="lang-python"><span class="hljs-comment">#the web endpoint</span>
<span class="hljs-meta">@app.get("/users/{user}")</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_user</span>(<span class="hljs-params">user = Depends(<span class="hljs-params">user_dep</span>)</span>) -&gt; dict:</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> user:
        <span class="hljs-keyword">raise</span> HTTPException(status_code=<span class="hljs-number">401</span>, detail=<span class="hljs-string">"Invalid username or password"</span>)
    <span class="hljs-keyword">return</span> user
</code></pre>
<p>The <code>user_dep</code> function is injected into the path operation using <code>Depends()</code>. When an HTTP request is made to this endpoint, FastAPI executes the dependency first, validates the input, and passes its return value to the <code>user</code> parameter.</p>
<p>The <code>-&gt; dict:</code> annotation indicates that the function returns a dictionary, which FastAPI auto-converts to JSON. If no matching record is found, an <code>HTTPException</code> with a 401 status code is raised; otherwise, the verified user data is returned.</p>
<p>Now you’ll start the FastAPI server. To start the server, open your terminal in the project directory and run:</p>
<pre><code class="lang-python">uvicorn function_deps:app --reload
</code></pre>
<ul>
<li><p><code>function_deps</code> is the name of your Python file (without the <strong>.py</strong> extension).</p>
</li>
<li><p><code>--reload</code> automatically restarts the server whenever you save changes.</p>
</li>
</ul>
<p>Once it starts, you’ll see an output similar to the image below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1762651145390/479b187c-f455-4617-aa7f-e075bf668ee5.jpeg" alt="uvicorn output in terminal" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Now you can test the endpoint. Open your browser or the Postman desktop app to validate the user <strong>“Seke”</strong>. Paste this URL into your browser: <em>http://127.0.0.1:8000/users/{user}?name=Seke&amp;password=SK99!</em></p>
<p>Alternatively, you can test the endpoint using FastAPI’s built-in docs at: http://127.0.0.1:8000/docs</p>
<p>In the Swagger UI:</p>
<ul>
<li><p>Click on the <strong>Get User</strong> endpoint</p>
</li>
<li><p>Click <strong>Try it out</strong></p>
</li>
<li><p>Enter “Seke” in the name field and “SK99!” in the password field</p>
</li>
<li><p>Click <strong>Execute</strong></p>
</li>
</ul>
<p>You should get a 200 status code, with the payload in this image:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1762651845087/9495107e-1ab8-4349-a701-04e5de461fb6.jpeg" alt="payload for get_user endpoint" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>You can also test the endpoint with usernames or passwords that don’t exist in the database. Each time, you should see a <strong>401</strong> error like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1762652045213/c8dc8bb1-e2c4-456f-92f5-911dddae73eb.jpeg" alt="unauthorized error output in FastAPI docs" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-use-class-dependencies-in-fastapi">How to Use Class Dependencies in FastAPI</h3>
<p>While functions are the most common way to define dependencies, FastAPI also supports class-based dependencies. Classes are useful when you need reusable instances with configurable state or prefer object-oriented patterns.</p>
<p>Class dependencies inject the same way: through the <code>Depends</code> function in your path operation.</p>
<p>Let's convert the <code>user_dep</code> function dependency to a class. It will authenticate users, grant access to valid credentials, and raise exceptions for unauthorized attempts. We'll apply it to a user dashboard endpoint to ensure only authenticated users access their resources.</p>
<pre><code class="lang-python"><span class="hljs-comment">#Dependency class for user authentication</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserAuth</span>():</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name: str, password: str</span>):</span>
        self.name = name
        self.password = password

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-comment">#check if name and password entered correspond to any row in the db</span>
        <span class="hljs-keyword">for</span> user <span class="hljs-keyword">in</span> users:
            <span class="hljs-keyword">if</span> user[<span class="hljs-string">"name"</span>] == self.name <span class="hljs-keyword">and</span> user[<span class="hljs-string">"password"</span>] == self.password:
                <span class="hljs-keyword">pass</span>
        <span class="hljs-comment">#If no match found, raise an error</span>
        <span class="hljs-keyword">raise</span> HTTPException(status_code=<span class="hljs-number">401</span>, detail=<span class="hljs-string">"Invalid username or password"</span>)
</code></pre>
<p>The <code>__init</code>__ method receives the parameters from the request (<code>name</code> and <code>password</code>) and stores them as instance attributes. These can then be accessed in the <code>__call__</code> method, which contains the dependency logic.</p>
<p>Note that <code>__call__</code> doesn't return a value in this example. It simply raises an <code>HTTPException</code> if authentication fails. The <code>__call__</code> method makes the class instance callable, allowing FastAPI to invoke it like a regular function.</p>
<p>Here’s how to inject <code>UserAuth</code> into a path function:</p>
<pre><code class="lang-python"><span class="hljs-comment">#Injecting the class dependency into a path operation</span>
<span class="hljs-meta">@app.get("/user/dashboard")</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_dashboard</span>(<span class="hljs-params">user: UserAuth = Depends(<span class="hljs-params">UserAuth</span>)</span>):</span>
    <span class="hljs-keyword">return</span> {<span class="hljs-string">"message"</span>: <span class="hljs-string">f"Access granted to <span class="hljs-subst">{user.name}</span>"</span>}
</code></pre>
<p><strong>What's happening here:</strong></p>
<p>When a client requests the <code>/user/dashboard</code> endpoint, FastAPI executes the dependency first. Recognizing <code>UserAuth</code> as a class, FastAPI automatically creates an instance and populates it with values from the query parameters.</p>
<p>Here’s the execution flow to help you understand:</p>
<ul>
<li><p><code>Depends(UserAuth)</code> tells FastAPI: “Before running this route, create a <code>UserAuth</code> instance.”</p>
</li>
<li><p>FastAPI extracts name and password from the request URL (for example, <em>/user/dashboard?name=Seke&amp;password=SK99!</em>).</p>
</li>
<li><p>It then calls <code>UserAuth(name=”Seke”, password=”SK99!”)</code> to create the instance.</p>
</li>
</ul>
<ul>
<li><p>The <code>UserAuth</code> instance, with its stored name and password attributes, is passed to the <code>user</code> parameter in <code>get_dashboard</code>.</p>
</li>
<li><p>The route function can access <code>user.name</code> and <code>user.password</code> directly.</p>
</li>
<li><p>If <code>__call__</code> raises an exception, the route never executes.</p>
</li>
</ul>
<p>Test the endpoint with valid credentials from the users list, and you should see output like this: </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1762655384549/ac5ab413-0f75-4711-8166-4c99bcca9d7c.jpeg" alt="class dependency output" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>A closer look at <a target="_blank" href="https://fastapi.tiangolo.com/tutorial/dependencies/classes-as-dependencies/#use-it">FastAPI’s official documentation</a> provides an alternative approach to classes as dependencies. However, using the <code>__call__</code> method, in my opinion, is the most straightforward and self-contained approach. It keeps your authentication logic modular without adding extra code to the path operation.</p>
<p>The trade-off is that class dependencies are more verbose than helper functions, but cleaner for complex logic.</p>
<h2 id="heading-dependency-scope">Dependency Scope</h2>
<p>FastAPI offers two ways to inject dependencies into a path operation: as a <strong>function parameter</strong> or via the <strong>path decorator</strong>. When you include a dependency as a function parameter, the dependency's return value is available within the function. But when injected into the decorator, the dependency executes without passing a return value to the path function.</p>
<p>Beyond single endpoints, FastAPI lets you inject dependencies at the router or global level. Let’s examine these scopes in more detail.</p>
<h3 id="heading-path-operation-level">Path Operation Level</h3>
<p>While the first example injected dependencies into path function parameters, you can also inject them directly into the decorator using the <code>dependencies</code> parameter. This approach is useful for side-effects (for example, authentication guards, rate limiting or request logging) where the return data is not required in the path operation.</p>
<p>Replace the previous code in <code>fastapi-deps/function_deps.py</code> with this:</p>
<pre><code class="lang-python"><span class="hljs-comment">#dep function to pass in decorator</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">user_dep</span>(<span class="hljs-params">name: str, password: str</span>):</span>
    <span class="hljs-keyword">for</span> u <span class="hljs-keyword">in</span> users:
        <span class="hljs-keyword">if</span> u[<span class="hljs-string">"name"</span>] == name <span class="hljs-keyword">and</span> u[<span class="hljs-string">"password"</span>] == password:
            <span class="hljs-keyword">return</span>
    <span class="hljs-keyword">raise</span> HTTPException(status_code=<span class="hljs-number">401</span>, detail=<span class="hljs-string">"Invalid username or password"</span>)

<span class="hljs-comment">#path function</span>
<span class="hljs-meta">@app.get("/users/{user}", dependencies=[Depends(user_dep)])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_user</span>() -&gt; dict:</span>
    <span class="hljs-keyword">return</span> {<span class="hljs-string">"message"</span> : <span class="hljs-string">"Access granted!"</span>}
</code></pre>
<p>This decorator-based dependency acts as a pre-check before the endpoint executes. It validates credentials without passing any values to the path function. On authentication failure, FastAPI raises an HTTPException and prevents the path operation from running.</p>
<p>If you test this using a valid name and password from the in-memory database, your output should look like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1762656537394/06fc80cf-a8b2-44d2-8955-ec914be699ba.jpeg" alt="path decorator dependency output" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h3 id="heading-router-level">Router Level</h3>
<p>Injecting dependencies at the router level allows multiple endpoints to share common logic without repeating the dependency in each route.</p>
<p>We'll use the same <code>user_dep</code> function but inject it at the router level. Add these imports to <code>fastapi-deps/router_deps.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> fastapi <span class="hljs-keyword">import</span> APIRouter, Depends

<span class="hljs-comment">#import the dependency function</span>
<span class="hljs-keyword">from</span> function_deps <span class="hljs-keyword">import</span> user_dep
</code></pre>
<p>Then, create an <code>APIRouter</code> instance, passing your dependency to the <code>dependencies</code> parameter. This makes the dependency run automatically for every route you define under this router. </p>
<p>In this example, <code>user_dep</code> executes before <code>get_user()</code> and any other endpoints you add to the router, eliminating the need to declare it on each route.</p>
<pre><code class="lang-python">router = APIRouter(prefix=<span class="hljs-string">"/users"</span>, dependencies=[Depends(user_dep)])

<span class="hljs-comment">#define the routes with or without additional dependencies</span>
<span class="hljs-meta">@router.get("/{user}")</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_user</span>() -&gt; dict:</span>
    <span class="hljs-keyword">return</span> {<span class="hljs-string">"message"</span> : <span class="hljs-string">"Access granted!"</span>}
</code></pre>
<p>In your main application file (<code>app.py</code>), import the router and register it with your FastAPI application using <code>include_router()</code>. This makes all routes defined in the router accessible through your application.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> fastapi <span class="hljs-keyword">import</span> FastAPI
<span class="hljs-keyword">import</span> uvicorn
<span class="hljs-keyword">from</span> router_deps <span class="hljs-keyword">import</span> router <span class="hljs-keyword">as</span> user_router

app = FastAPI()
app.include_router(user_router)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    uvicorn.run(<span class="hljs-string">"app:app"</span>, reload=<span class="hljs-literal">True</span>)
</code></pre>
<p>Start your server and test the route using a valid name–password pair from the users list, then try a mismatched one. You should get a <strong>200</strong> status for the correct credentials and <strong>401</strong> for invalid ones.</p>
<h3 id="heading-application-level">Application Level</h3>
<p>Application-level dependencies (also called <em>global dependencies</em>) are defined when instantiating the FastAPI app and apply to every route in your application. Unlike router-level dependencies that target specific endpoint groups, app-level dependencies extend across the entire application. Any dependency injected into the FastAPI app object will automatically execute for all path functions.</p>
<p>Let's inject a simple <em>logging</em> dependency alongside the <em>user authentication</em> dependency we've used throughout this article. </p>
<p>Update <code>fastapi-deps/app.py</code> with this code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> fastapi <span class="hljs-keyword">import</span> FastAPI, Depends
<span class="hljs-keyword">import</span> uvicorn
<span class="hljs-keyword">from</span> function_deps <span class="hljs-keyword">import</span> user_dep
<span class="hljs-keyword">from</span> router_deps <span class="hljs-keyword">import</span> router <span class="hljs-keyword">as</span> user_router
<span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime

<span class="hljs-comment">#Basic logging dependency</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">log_request</span>():</span>
    print(<span class="hljs-string">f"[<span class="hljs-subst">{datetime.now()}</span>] Request received."</span>)

app = FastAPI(dependencies=[Depends(log_request), Depends(user_dep)])
app.include_router(user_router)

<span class="hljs-meta">@app.get("/home")</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_main</span>():</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Welcome back!!!"</span>


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    uvicorn.run(<span class="hljs-string">"app:app"</span>, reload=<span class="hljs-literal">True</span>)
</code></pre>
<p>When you send a request to any endpoint within this application, <code>log_request</code> acknowledges it and outputs what time the request was made. Since we aren’t sending the logs to any database in particular, it will just print to the terminal (or console) like so:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1762673203094/d1c43e1b-0cc2-46e5-ae54-ee4849d1af66.jpeg" alt="logging dependency output in console" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Request the endpoint with valid credentials using your browser, cURL, Postman, or the Swagger UI. You should get this response:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1762673465276/28d90221-4feb-4467-8c6c-8557dd54de03.jpeg" alt="Server response for API request to home page" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Although the same authentication and logging logic apply to all registered routers, the specific message users see depends on what you program into each router.</div>
</div>

<h2 id="heading-common-use-cases-for-dependency-injection">Common Use Cases for Dependency Injection</h2>
<p>Dependency injection solves several common challenges in API development. Here are the most frequent use cases where you'll apply this pattern.</p>
<ol>
<li><p><strong>Database Connections:</strong> Reusing connection logic across multiple endpoints prevents connection leaks, and ensures each request has an isolated session.</p>
</li>
<li><p><strong>Authentication &amp; Authorization:</strong> Dependencies help validate tokens and verify user roles across protected routes. </p>
</li>
<li><p><strong>Logging &amp; Monitoring:</strong> A logging dependency can automatically record each request to your monitoring system or database. It is beneficial for debugging and tracking API usage.</p>
</li>
<li><p><strong>Rate Limiting:</strong> You can control request frequency and prevent API abuse by injecting rate-limiting logic in path functions.</p>
</li>
<li><p><strong>Configuration &amp; Settings:</strong> FastAPI’s dependency injection system simplifies configuration management by letting you inject settings such as API keys or environment variables wherever needed, keeping your code consistent.</p>
</li>
<li><p><strong>Pagination &amp; Filtering:</strong> Injecting common parameters like page_size and limit standardize data retrieval patterns across endpoints. </p>
</li>
</ol>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>FastAPI's dependency injection system helps you manage shared logic and resources efficiently while adhering to <em>DRY</em> principles. However, knowing when to inject a dependency versus when to skip it is a skill that comes with practice.</p>
<p>Dependency injection isn't needed for simple, standalone logic. But for resources requiring lifecycle management, shared logic, or modularity, FastAPI's dependency injection system simplifies checks and app operations—with or without return values.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Implement Dependency Injection in Go - Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Regardless of their initial size or scope, projects tend to grow in complexity over time. As new features are added and requirements evolve, the number of components and the connections between them multiply. Services, handlers, repositories, externa... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-dependency-injection-in-go/</link>
                <guid isPermaLink="false">68d44505e26e6f1a24c44ba9</guid>
                
                    <category>
                        <![CDATA[ Go Language ]]>
                    </category>
                
                    <category>
                        <![CDATA[ dependency injection ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Gabor Koos ]]>
                </dc:creator>
                <pubDate>Wed, 24 Sep 2025 19:22:45 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1758741125008/e796d218-2cf6-43ed-87a5-dfc772e121f8.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Regardless of their initial size or scope, projects tend to grow in complexity over time. As new features are added and requirements evolve, the number of components and the connections between them multiply. Services, handlers, repositories, external clients, and more all become intertwined, making it increasingly difficult to keep track of what depends on what.</p>
<p>This growing web of dependencies can quickly become a problem. When the relationships between components are unclear or tightly coupled, the codebase becomes harder to test, refactor, and maintain. Making changes or adding new features can introduce unexpected bugs, and isolating parts of the system for testing often requires pulling in far more than you intended.</p>
<p>Consider a team working on a backend service. At first, the codebase is manageable: a few handlers, a database connection, maybe a logger. But as the product matures, new requirements appear: authentication, caching, integrations with third-party APIs, background jobs, and more. Suddenly, a single handler might need access to several services, each with their own dependencies. The team finds themselves spending more time figuring out what needs what, and less time actually building features. Testing becomes a headache, and refactoring feels risky.</p>
<p>Why is this such a challenge? When dependencies are hidden inside components, it's hard to see how everything fits together. Tightly coupled code means that a change in one place can ripple unpredictably through the system. It's easy to end up with fragile code that's difficult to test, hard to extend, and risky to modify.</p>
<p>One way to address this challenge is dependency injection - often referred to as DI. The core idea is straightforward: instead of having each part of a program create its own dependencies, those dependencies are provided from the outside. This makes the relationships between components explicit, allowing for easier testing, swapping of implementations, and greater flexibility as the project evolves.</p>
<p>DI isn't about frameworks or enterprise patterns, it's a practical technique for structuring code so that complexity remains manageable. By making dependencies clear and configurable, DI helps keep code maintainable and adaptable, no matter how requirements change.</p>
<p>In this tutorial, we'll cover:</p>
<ul>
<li><p>What dependency injection is in Go.</p>
</li>
<li><p>How to implement manual DI, the idiomatic way.</p>
</li>
<li><p>When manual DI becomes unwieldy.</p>
</li>
<li><p>Popular DI libraries in Go.</p>
</li>
<li><p>Best practices for managing dependencies in real-world projects.</p>
</li>
</ul>
<p>By the end of this guide, you'll have a clear understanding of DI in Go and know how to choose the right approach for your projects.</p>
<h2 id="heading-what-well-cover">What We’ll Cover:</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-dependency-injection">What is Dependency Injection?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-manual-di-in-go">Manual DI in Go</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-the-repository-layer">The Repository Layer</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-service-layer">The Service Layer</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-handler-layer">The Handler Layer</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wiring-it-all-together-in-maingo">Wiring It All Together in main.go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-manual-di-works-well-in-go">Why Manual DI Works Well in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-downsides-of-manual-di">Downsides of Manual DI</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-a-quick-testing-example">A Quick Testing Example</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-takeaway">Takeaway</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-exercise-for-the-reader">Exercise for the Reader</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-when-di-gets-hard">When DI Gets Hard</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-nested-dependencies">Nested Dependencies</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-testing-at-scale">Testing at Scale</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-configuration-complexity">Configuration Complexity</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-patterns-to-mitigate-complexity">Patterns to Mitigate Complexity</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-developers-consider-di-frameworks">When Developers Consider DI Frameworks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-key-takeaways">Key Takeaways</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-go-di-libraries-and-tools">Go DI Libraries and Tools</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-google-wire-compile-time-di">Google Wire (Compile-Time DI)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-uber-dig-runtime-di">Uber Dig (Runtime DI)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-uber-fx-di-app-lifecycle">Uber Fx (DI + App Lifecycle)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-other-lightweight-di-helpers">Other Lightweight DI Helpers</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-choosing-the-right-tool">Choosing the Right Tool</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-key-takeaways-1">Key Takeaways</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-exercise-for-the-reader-1">Exercise for the Reader</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-best-practices-and-takeaways">Best Practices and Takeaways</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-prefer-explicit-dependencies">Prefer Explicit Dependencies</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-start-simple-manual-di">Start Simple (Manual DI)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-frameworks-to-tame-complexity">Use Frameworks to Tame Complexity</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-keep-wiring-at-the-edges">Keep Wiring at the Edges</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-favor-interfaces-for-testability">Favor Interfaces for Testability</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-avoid-over-engineering">Avoid Over-Engineering</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-balance-verbosity-and-magic">Balance Verbosity and Magic</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-adopt-incrementally">Adopt Incrementally</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-document-your-wiring">Document Your Wiring</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-key-takeaways-2">Key Takeaways</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>This article assumes you understand the basics of Go. You don't need to be an expert, but you should be comfortable with:</p>
<ul>
<li><p>Functions and structs – understanding how to define types and their methods.</p>
</li>
<li><p>Interfaces – knowing how to declare and implement them.</p>
</li>
<li><p>Packages and imports – organizing code across files and packages.</p>
</li>
<li><p>Basic Go web server – familiarity with <code>net/http</code> and simple handlers will help when we build examples.</p>
</li>
</ul>
<p>If you've read the earlier freeCodeCamp guides on Go collections and standard library helpers, you're in good shape. If not, don't worry - all code examples here are self-contained and explained step by step.</p>
<p>You'll also need:</p>
<ul>
<li><p>Go installed (1.20 or later recommended)</p>
</li>
<li><p>A text editor or IDE of your choice</p>
</li>
<li><p>Be comfortable running go run from the terminal</p>
</li>
</ul>
<p>That's it. No special libraries are required unless we explicitly install them in later sections (for example, when we explore <code>wire</code>, <code>dig</code>, or <code>fx</code>).</p>
<h2 id="heading-what-is-dependency-injection">What is Dependency Injection?</h2>
<p>Let's start with a simple example. Imagine a web handler that fetches a user from a database. Without DI, it might look like this:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> UserService <span class="hljs-keyword">struct</span>{}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(us *UserService)</span> <span class="hljs-title">GetUser</span><span class="hljs-params">(id <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">string</span></span> {
    <span class="hljs-comment">// Pretend we fetch a user from the database</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">"user"</span>
}

<span class="hljs-keyword">type</span> Handler <span class="hljs-keyword">struct</span> {
    userService UserService
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(h *Handler)</span> <span class="hljs-title">ServeHTTP</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
    user := h.userService.GetUser(<span class="hljs-number">1</span>)
    fmt.Fprintln(w, user)
}
</code></pre>
<p>Here, <code>Handler</code> is tightly coupled to <code>UserService</code>. We can't easily swap out <code>UserService</code> for a mock in tests or replace it with a different implementation.</p>
<p>With dependency injection, we pass the dependency into the struct, usually via a constructor function:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> UserService <span class="hljs-keyword">interface</span> {
    GetUser(id <span class="hljs-keyword">int</span>) <span class="hljs-keyword">string</span>
}

<span class="hljs-keyword">type</span> Handler <span class="hljs-keyword">struct</span> {
    userService UserService
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewHandler</span><span class="hljs-params">(us UserService)</span> *<span class="hljs-title">Handler</span></span> {
    <span class="hljs-keyword">return</span> &amp;Handler{userService: us}
}
</code></pre>
<p>Now <code>Handler</code> doesn't care how the <code>UserService</code> is created. That decision is left to the calling code (<code>main.go</code> or a test). This is the essence of DI: you inject what a component needs rather than letting it create it internally.</p>
<p>This approach has several benefits:</p>
<ul>
<li><p><strong>Testability</strong>: You can easily pass a mock or fake <code>UserService</code> when testing <code>Handler</code>.</p>
</li>
<li><p><strong>Flexibility</strong>: You can swap out implementations without changing <code>Handler</code>.</p>
</li>
<li><p><strong>Separation of Concerns</strong>: Each component focuses on its own logic without worrying about how its dependencies are created.</p>
</li>
</ul>
<p>As you can see, the concept is quite simple, but it has powerful implications for how you structure your code. Explicitly managing dependencies has many benefits and barely any downsides. Maybe you have to write some extra boilerplate, but this is a small price to pay for the clarity and flexibility it brings.</p>
<p>The principle of dependency injection is not unique to Go, it's a general software design principle you can find in many programming languages. However, the way you implement it can vary by language, ecosystem, and your specific use case. It's a recurring theme in higher-level design patterns: they tell you what to achieve, but they are not bothered with the details of how to implement it.</p>
<p>So the key idea is to explicitly manage dependencies by passing them in, rather than letting components fetch or create them themselves. This can be done a couple of ways:</p>
<ul>
<li><p><strong>Constructor Injection</strong>: As shown above, dependencies are provided via constructor functions. This is the most common and idiomatic way in Go.</p>
</li>
<li><p><strong>Field Injection</strong>: Dependencies are set directly on struct fields. This is less common in Go and not considered idiomatic, but can be useful in some scenarios.</p>
</li>
<li><p><strong>Method Injection</strong>: Dependencies are passed as parameters to methods. This is also less common in Go, but can be useful in certain situations.</p>
</li>
</ul>
<p>The most universal approach in Go is constructor injection. Field and Method injection is less common, mainly because they can lead to less clear code and harder-to-track dependencies (it's always better to see what a component needs upfront in the constructor than to have it hidden in method calls or field assignments).</p>
<h2 id="heading-manual-di-in-go">Manual DI in Go</h2>
<p>The most common and idiomatic way to handle dependencies in Go is to wire them manually. That might sound boring, but it's actually one of Go's strengths: you always know where a dependency comes from, and nothing is hidden behind a framework. Especially if you inject dependencies via constructors, it's always clear what a component needs in order to work properly. This explicitness is a key part of Go's philosophy: you make the dependencies obvious and explicit, so that anyone reading the code can easily understand how components fit together.</p>
<p>Let's build a small web application with three layers to see how this works in practice:</p>
<ul>
<li><p>A <strong>repository</strong> that talks to the database.</p>
</li>
<li><p>A <strong>service</strong> that contains business logic.</p>
</li>
<li><p>A <strong>handler</strong> that exposes an HTTP endpoint.</p>
</li>
</ul>
<p>We'll then wire these pieces together in <code>main.go</code>.</p>
<h3 id="heading-the-repository-layer">The Repository Layer</h3>
<p>At the bottom of the stack, we'll define a <code>UserRepository</code>. In a real-world project, this would talk to a database, but for simplicity we’ll just return some dummy data.</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> UserRepository <span class="hljs-keyword">struct</span> {
    <span class="hljs-comment">// Imagine this struct holds a database client</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewUserRepository</span><span class="hljs-params">()</span> *<span class="hljs-title">UserRepository</span></span> {
    <span class="hljs-keyword">return</span> &amp;UserRepository{}
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(r *UserRepository)</span> <span class="hljs-title">FindUser</span><span class="hljs-params">(id <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">string</span></span> {
    <span class="hljs-comment">// In a real app, this would query the database</span>
    <span class="hljs-keyword">return</span> fmt.Sprintf(<span class="hljs-string">"user-%d"</span>, id)
}
</code></pre>
<p>The key thing here is the constructor <code>NewUserRepository()</code>. This is a Go convention:</p>
<ul>
<li><p>Functions named <code>NewXxx</code> create and return new instances.</p>
</li>
<li><p>They make wiring dependencies explicit.</p>
</li>
</ul>
<p>(We call it a "constructor" because Go doesn't have constructors in the traditional OOP sense. Instead, we use functions that return initialized structs, which is closer to factory functions, but the term "constructor" is commonly used in Go parlance.)</p>
<h3 id="heading-the-service-layer">The Service Layer</h3>
<p>Above the repository, we'll add a service that uses it:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> UserService <span class="hljs-keyword">struct</span> {
    repo *UserRepository
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewUserService</span><span class="hljs-params">(r *UserRepository)</span> *<span class="hljs-title">UserService</span></span> {
    <span class="hljs-keyword">return</span> &amp;UserService{repo: r}
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *UserService)</span> <span class="hljs-title">GetUser</span><span class="hljs-params">(id <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">string</span></span> {
    <span class="hljs-comment">// Add some business logic here</span>
    <span class="hljs-keyword">return</span> s.repo.FindUser(id)
}
</code></pre>
<p>The <code>UserService</code> depends on the repository. Notice that the dependency is passed into the "constructor". This is dependency injection in action: instead of <code>UserService</code> creating its own repository, we give it one.</p>
<p>This also makes the service easy to test. In tests, we can pass a fake repository instead of the real one.</p>
<h3 id="heading-the-handler-layer">The Handler Layer</h3>
<p>Finally, at the top, let's add a web handler. This is what responds to HTTP requests:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Handler <span class="hljs-keyword">struct</span> {
    service *UserService
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewHandler</span><span class="hljs-params">(s *UserService)</span> *<span class="hljs-title">Handler</span></span> {
    <span class="hljs-keyword">return</span> &amp;Handler{service: s}
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(h *Handler)</span> <span class="hljs-title">ServeHTTP</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
    user := h.service.GetUser(<span class="hljs-number">1</span>)
    fmt.Fprintln(w, user)
}
</code></pre>
<p>The handler depends on the service. Again, we inject the dependency through the constructor.</p>
<h3 id="heading-wiring-it-all-together-in-maingo">Wiring It All Together in <code>main.go</code></h3>
<p>Now we need to put the pieces together. Going from the bottom up, we create the repository, then the service, and finally the handler. This is done in <code>main.go</code>:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    repo := NewUserRepository()      <span class="hljs-comment">// lowest layer</span>
    service := NewUserService(repo)  <span class="hljs-comment">// depends on repo</span>
    handler := NewHandler(service)   <span class="hljs-comment">// depends on service</span>

    http.Handle(<span class="hljs-string">"/user"</span>, handler)
    http.ListenAndServe(<span class="hljs-string">":8080"</span>, <span class="hljs-literal">nil</span>)
}
</code></pre>
<p>Here, <code>main()</code> is responsible for wiring everything together. This is a simple and clear way to manage dependencies:</p>
<ul>
<li><p>Each component declares what it needs via its constructor.</p>
</li>
<li><p><code>main()</code> creates and connects everything.</p>
</li>
<li><p>The flow of dependencies is explicit and easy to follow.</p>
</li>
<li><p>No hidden magic: everything is plain Go code, no frameworks or reflection.</p>
</li>
</ul>
<p>If you run this program and visit <code>http://localhost:8080/user</code>, you'll see:</p>
<pre><code class="lang-bash">user-1
</code></pre>
<p>That's it. We've manually injected each dependency and wired everything together in <code>main()</code>. We have full control over how components are created and connected. We can easily swap out implementations, add new layers, or change the wiring as needed.</p>
<h3 id="heading-why-manual-di-works-well-in-go">Why Manual DI Works Well in Go</h3>
<p>This style of dependency management is the default in Go. It has several advantages:</p>
<ul>
<li><p>Explicit, clear dependencies: Every dependency is visible in the constructor. If <code>UserService</code> needs a repository, you see it right there in <code>NewUserService()</code>. Nothing is hidden.</p>
</li>
<li><p>No magic: There are no reflection tricks, no hidden containers, no annotations. When you look at <code>main.go</code>, you see exactly how the application is assembled.</p>
</li>
<li><p>Easy to test: Because dependencies are injected, you can pass mocks or stubs in tests. For example, you might create a <code>FakeUserRepository</code> and pass it to <code>NewUserService()</code> in a unit test. (And your <code>fakeUserRepository</code> would likely resemble the <code>UserRepository</code> above.)</p>
</li>
<li><p>Great for small and medium apps: For most projects, this approach is all you need. Many production Go services at big companies use nothing more than manual DI.</p>
</li>
</ul>
<h3 id="heading-downsides-of-manual-di">Downsides of Manual DI</h3>
<p>Of course, nothing is perfect. Manual DI has some drawbacks, especially as your application grows:</p>
<ul>
<li><p>Verbose <code>main.go</code>: As the number of services increases, <code>main.go</code> can become a wall of wiring code. You may have dozens of lines just creating and passing around dependencies. The same approach that works so well for small or medium apps can become unwieldy in very large projects.</p>
</li>
<li><p>Nested dependencies: Imagine service A depends on service B, which depends on service C, which depends on a repository. By the time you wire everything in <code>main.go</code>, you might end up with long chains of constructor calls. Unlike our previous example, imagine hundreds of services and repositories. This can make the wiring code almost impossible to read and maintain.</p>
</li>
<li><p>Scaling pain: In very large applications with many modules, it can be hard to keep track of which service depends on which other service. Once your application reaches a certain size, manual DI may no longer be sufficient. This is where various DI frameworks come in, as we'll see in a bit.</p>
</li>
</ul>
<h3 id="heading-a-quick-testing-example">A Quick Testing Example</h3>
<p>To see the benefit of manual DI, let's write a quick test. Suppose we want to test <code>UserService</code> without touching the real repository. We can define a fake repository:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> FakeUserRepository <span class="hljs-keyword">struct</span>{}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(f *FakeUserRepository)</span> <span class="hljs-title">FindUser</span><span class="hljs-params">(id <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">string</span></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"fake-user"</span>
}
</code></pre>
<p>And then inject this into the service:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestUserService</span><span class="hljs-params">(t *testing.T)</span></span> {
    fakeRepo := &amp;FakeUserRepository{}
    service := NewUserService(fakeRepo)

    got := service.GetUser(<span class="hljs-number">1</span>)
    want := <span class="hljs-string">"fake-user"</span>

    <span class="hljs-keyword">if</span> got != want {
        t.Errorf(<span class="hljs-string">"got %s, want %s"</span>, got, want)
    }
}
</code></pre>
<p>This test is only possible because we injected the dependency. If <code>UserService</code> had created its own repository internally, we wouldn't be able to replace it.</p>
<h3 id="heading-takeaway">Takeaway</h3>
<p>Manual DI in Go is simple, explicit, and powerful. It's the idiomatic way to manage dependencies in Go applications. For many projects, it's all you'll ever need. In an ideal world, this article would end here and everybody could go on their merry way to build great software.</p>
<p>But as we'll see in the next section, when your project grows large and your wiring code gets out of hand, manual DI can start to feel painful. That's when developers often look for frameworks or tools to help.</p>
<h3 id="heading-exercise-for-the-reader">Exercise for the Reader</h3>
<p>We provided all the relevant code snippets in this section, but you can try building the full application yourself. Create a new Go module, add the repository, service, and handler layers as shown, and wire them together in <code>main.go</code>. Run the server and visit the endpoint to see it in action. Then, try writing a test for <code>UserService</code> using a fake repository. This hands-on practice will help solidify your understanding of manual DI in Go.</p>
<h2 id="heading-when-di-gets-hard">When DI Gets Hard</h2>
<p>Manual dependency injection works beautifully in small to medium Go projects. It's explicit, testable, and easy to reason about. But as your application grows, wiring dependencies manually can become cumbersome. In this section, we'll explore the pain points that arise when manual DI scales, and why developers sometimes reach for DI frameworks or libraries.</p>
<h3 id="heading-nested-dependencies">Nested Dependencies</h3>
<p>Consider a slightly larger project with multiple services:</p>
<ul>
<li><p><code>AuthService</code> depends on <code>UserService</code>.</p>
</li>
<li><p><code>UserService</code> depends on <code>UserRepository</code>.</p>
</li>
<li><p><code>EmailService</code> depends on an <code>SMTPClient</code>.</p>
</li>
<li><p><code>NotificationService</code> depends on both <code>EmailService</code> and <code>SMSService</code>.</p>
</li>
<li><p><code>Handler</code> depends on <code>AuthService</code> and <code>NotificationService</code>.</p>
</li>
</ul>
<p>If you try to wire all of this manually, your <code>main.go</code> starts to look like this:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    userRepo := NewUserRepository()
    userService := NewUserService(userRepo)
    authService := NewAuthService(userService)

    smtpClient := NewSMTPClient(<span class="hljs-string">"smtp.example.com"</span>)
    emailService := NewEmailService(smtpClient)
    smsService := NewSMSService()
    notificationService := NewNotificationService(emailService, smsService)

    handler := NewHandler(authService, notificationService)

    http.Handle(<span class="hljs-string">"/signup"</span>, handler)
    http.ListenAndServe(<span class="hljs-string">":8080"</span>, <span class="hljs-literal">nil</span>)
}
</code></pre>
<p>This example is already verbose and hard to read, even though the application isn't very large. Imagine what happens when dozens of services and repositories are involved.</p>
<p>Problems you might notice:</p>
<ul>
<li><p>Long chains of dependencies: Services depend on other services, which depend on repositories, which might depend on database clients. The chain grows quickly and can be hard to manage.</p>
</li>
<li><p>Wiring logic in <code>main.go</code>: <code>main.go</code> becomes full of constructor calls. While explicit, it can be difficult to see the overall structure of the application at a glance.</p>
</li>
<li><p>Increased risk of mistakes: Passing the wrong dependency to a constructor or forgetting to wire a new service can cause runtime errors. Manual DI requires careful attention as projects scale.</p>
</li>
</ul>
<h3 id="heading-testing-at-scale">Testing at Scale</h3>
<p>Another challenge arises when testing large applications. Suppose you want to write integration tests for <code>Handler</code> with fake dependencies. You'll need to manually create fakes or mocks for every layer:</p>
<pre><code class="lang-go">fakeRepo := &amp;FakeUserRepository{}
fakeUserService := NewUserService(fakeRepo)
fakeAuthService := NewAuthService(fakeUserService)
fakeEmailService := &amp;FakeEmailService{}
fakeSMSService := &amp;FakeSMSService{}
fakeNotificationService := NewNotificationService(fakeEmailService, fakeSMSService)
handler := NewHandler(fakeAuthService, fakeNotificationService)
</code></pre>
<p>While this works, the test setup becomes verbose and repetitive, especially if multiple tests require different combinations of fake dependencies. This verbosity can make tests very hard to maintain.</p>
<h3 id="heading-configuration-complexity">Configuration Complexity</h3>
<p>Some services require configuration or external clients, such as:</p>
<ul>
<li><p>Database connections</p>
</li>
<li><p>HTTP clients</p>
</li>
<li><p>API keys or credentials</p>
</li>
<li><p>Logging frameworks</p>
</li>
</ul>
<p>In manual DI, you often end up writing repetitive code to initialize and pass these dependencies around:</p>
<pre><code class="lang-go">db := NewDatabase(<span class="hljs-string">"postgres://user:pass@localhost:5432/db"</span>)
logger := NewLogger(<span class="hljs-string">"INFO"</span>)
repo := NewUserRepository(db, logger)
service := NewUserService(repo, logger)
handler := NewHandler(service, logger)
</code></pre>
<p>As the number of dependencies grows, it's easy to forget a required parameter or misconfigure a service. This can result in runtime errors that are difficult to debug.</p>
<h3 id="heading-patterns-to-mitigate-complexity">Patterns to Mitigate Complexity</h3>
<p>Even without frameworks, there are some strategies to keep manual DI manageable:</p>
<ol>
<li><strong>Group related dependencies</strong>: If multiple services depend on the same configuration or clients, bundle them into a struct:</li>
</ol>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> AppDeps <span class="hljs-keyword">struct</span> {
    DB     *Database
    Logger *Logger
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewAppDeps</span><span class="hljs-params">()</span> *<span class="hljs-title">AppDeps</span></span> {
    db := NewDatabase(<span class="hljs-string">"..."</span>)
    logger := NewLogger(<span class="hljs-string">"INFO"</span>)
    <span class="hljs-keyword">return</span> &amp;AppDeps{DB: db, Logger: logger}
}
</code></pre>
<p>This reduces repetitive constructor parameters:</p>
<pre><code class="lang-go">deps := NewAppDeps()
repo := NewUserRepository(deps.DB, deps.Logger)
service := NewUserService(repo, deps.Logger)
</code></pre>
<ol start="2">
<li><strong>Layered constructors</strong>: Create higher-level constructors for feature modules:</li>
</ol>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewUserModule</span><span class="hljs-params">(deps *AppDeps)</span> <span class="hljs-params">(*UserService, *UserHandler)</span></span> {
    repo := NewUserRepository(deps.DB, deps.Logger)
    service := NewUserService(repo, deps.Logger)
    handler := NewHandler(service)
    <span class="hljs-keyword">return</span> service, handler
}
</code></pre>
<p>This keeps <code>main.go</code> cleaner and encapsulates wiring for a specific module.</p>
<h3 id="heading-when-developers-consider-di-frameworks">When Developers Consider DI Frameworks</h3>
<p>Once your project grows beyond a handful of services, manual DI can become a maintenance burden:</p>
<ul>
<li><p>Long constructor chains</p>
</li>
<li><p>Verbose test setup</p>
</li>
<li><p>Repetitive wiring code</p>
</li>
</ul>
<p>This is where Go DI libraries like <code>Google Wire</code>, <code>Uber Dig</code>, or <code>Uber Fx</code> can help. They automate some of the wiring while keeping dependencies explicit. Frameworks are not strictly necessary, but they can make large-scale projects more manageable. In the next section, we'll explore some popular DI libraries in Go, how they work, and when to consider using them.</p>
<h3 id="heading-key-takeaways">Key Takeaways</h3>
<ul>
<li><p>Manual DI is explicit, simple, and idiomatic. It works best in small to medium applications.</p>
</li>
<li><p>As the number of dependencies grows, <code>main.go</code> can become long and repetitive.</p>
</li>
<li><p>Testing complex services requires careful setup of fakes or mocks.</p>
</li>
<li><p>Strategies like grouping dependencies or layered constructors can reduce boilerplate.</p>
</li>
<li><p>For very large applications, DI frameworks can help manage wiring, but manual DI remains the foundation of idiomatic Go.</p>
</li>
</ul>
<h2 id="heading-go-di-libraries-and-tools">Go DI Libraries and Tools</h2>
<p>Once your project grows beyond a handful of services, manually wiring all dependencies can become verbose and error-prone. That's where dependency injection libraries can help. Go doesn't force you to use them - manual DI is still idiomatic - but frameworks can simplify wiring in larger projects.</p>
<p>In this section, we'll explore some of the most popular Go DI tools:</p>
<ul>
<li><p>Google Wire (compile-time DI)</p>
</li>
<li><p>Uber Dig (runtime DI)</p>
</li>
<li><p>Uber Fx (DI with app lifecycle management)</p>
</li>
<li><p>A brief look at other lightweight DI helpers</p>
</li>
</ul>
<p>We'll show how each works, with examples, and discuss when to consider them.</p>
<h3 id="heading-google-wire-compile-time-di">Google Wire (Compile-Time DI)</h3>
<p><a target="_blank" href="https://github.com/google/wire">Google Wire</a> is a compile-time code generation tool. You define how dependencies relate to each other, and Wire generates the code to assemble them. There's no runtime magic, all the wiring is explicit in the generated code.</p>
<p><strong>Example: Wire in Action</strong></p>
<p>Suppose we have a simple service with a repository and handler:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> UserRepository <span class="hljs-keyword">struct</span>{}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewUserRepository</span><span class="hljs-params">()</span> *<span class="hljs-title">UserRepository</span></span> { <span class="hljs-keyword">return</span> &amp;UserRepository{} }

<span class="hljs-keyword">type</span> UserService <span class="hljs-keyword">struct</span> { repo *UserRepository }
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewUserService</span><span class="hljs-params">(r *UserRepository)</span> *<span class="hljs-title">UserService</span></span> { <span class="hljs-keyword">return</span> &amp;UserService{repo: r} }

<span class="hljs-keyword">type</span> Handler <span class="hljs-keyword">struct</span> { service *UserService }
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewHandler</span><span class="hljs-params">(s *UserService)</span> *<span class="hljs-title">Handler</span></span> { <span class="hljs-keyword">return</span> &amp;Handler{service: s} }
</code></pre>
<p>With Wire, we define a <em>provider set</em> and an <em>injector</em>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"github.com/google/wire"</span>

<span class="hljs-comment">// Provider set</span>
<span class="hljs-keyword">var</span> Set = wire.NewSet(NewUserRepository, NewUserService, NewHandler)

<span class="hljs-comment">// Injector function</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">InitializeHandler</span><span class="hljs-params">()</span> *<span class="hljs-title">Handler</span></span> {
    wire.Build(Set) <span class="hljs-comment">// generates code here to wire dependencies</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>
}
</code></pre>
<p><code>wire</code> has a CLI tool that generates the code to wire up your dependencies. When you run <code>wire</code> in your project, it generates Go code for <code>InitializeHandler()</code>, assembling all dependencies. You can then use it in <code>main.go</code>:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    handler := InitializeHandler()
    http.Handle(<span class="hljs-string">"/user"</span>, handler)
    http.ListenAndServe(<span class="hljs-string">":8080"</span>, <span class="hljs-literal">nil</span>)
}
</code></pre>
<p>So basically, you define the dependencies in the provider set, then annotate the injector function with <code>wire.Build(Set)</code>, and Wire generates the boilerplate for you in that function. The generated code is in a separate file.</p>
<p>Pros:</p>
<ul>
<li><p>No runtime overhead, wiring happens at compile-time.</p>
</li>
<li><p>Generated code is readable and explicit.</p>
</li>
<li><p>Safe: missing dependencies cause compile errors.</p>
</li>
</ul>
<p>Cons:</p>
<ul>
<li><p>Requires an extra tool (<code>wire</code> CLI).</p>
</li>
<li><p>Generated files add some noise to the codebase.</p>
</li>
<li><p>Not as flexible for dynamic runtime configuration.</p>
</li>
</ul>
<h3 id="heading-uber-dig-runtime-di">Uber Dig (Runtime DI)</h3>
<p><a target="_blank" href="https://github.com/uber-go/dig">Uber Dig</a> is a runtime dependency injection container. Unlike Wire, Dig uses reflection to automatically resolve dependencies when you invoke them.</p>
<p><strong>Example: Dig in Action</strong></p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"go.uber.org/dig"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    c := dig.New() <span class="hljs-comment">// create a new container</span>

    <span class="hljs-comment">// Provide constructors to the container</span>
    c.Provide(NewUserRepository)
    c.Provide(NewUserService)
    c.Provide(NewHandler)

    <span class="hljs-comment">// Invoke the function, letting Dig resolve dependencies</span>
    err := c.Invoke(<span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(h *Handler)</span></span> {
        http.Handle(<span class="hljs-string">"/user"</span>, h)
    })
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)
    }

    http.ListenAndServe(<span class="hljs-string">":8080"</span>, <span class="hljs-literal">nil</span>)
}
</code></pre>
<p>Here, Dig inspects the constructors' parameters and automatically provides the required dependencies. You no longer have to manually pass each dependency in <code>main()</code>. It creates a container, then <code>Provide()</code> registers constructors with the container. Dig analyzes the parameters of each constructor to understand what dependencies are needed. Then <code>c.Invoke(func(h *Handler) { ... })</code> asks Dig to call the provided function, automatically resolving and constructing all dependencies required for <code>*Handler</code> (using the registered constructors).</p>
<p>How Dig resolves dependencies:</p>
<ul>
<li><p>Dig looks at <code>NewHandler</code> and sees it needs a <code>*UserService</code>.</p>
</li>
<li><p>It looks at <code>NewUserService</code> and sees it needs a <code>*UserRepository</code>.</p>
</li>
<li><p>It calls the constructors in the correct order, passing the results as needed, and finally provides the fully constructed <code>*Handler</code> to your function.</p>
</li>
</ul>
<p>Does it look like magic? A bit, but it's all based on reflection and the constructors you provide. You still have full control over how dependencies are created, but Dig handles the wiring for you.</p>
<p>Pros:</p>
<ul>
<li><p>Reduces manual wiring, especially in large projects.</p>
</li>
<li><p>Flexible: easy to swap implementations at runtime.</p>
</li>
<li><p>Works well with dynamic configurations.</p>
</li>
</ul>
<p>Cons:</p>
<ul>
<li><p>Uses reflection, which can introduce runtime errors if dependencies are misconfigured.</p>
</li>
<li><p>Less explicit: it's not always obvious how a dependency is resolved.</p>
</li>
<li><p>Debugging runtime DI issues can be tricky.</p>
</li>
<li><p>Reflection can have performance implications, though usually negligible.</p>
</li>
</ul>
<h3 id="heading-uber-fx-di-app-lifecycle">Uber Fx (DI + App Lifecycle)</h3>
<p><a target="_blank" href="https://github.com/uber-go/fx">Uber Fx</a> builds on Dig and adds application lifecycle management. It's ideal for large microservices with multiple modules and background processes.</p>
<p><strong>Example: Fx in Action</strong></p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"go.uber.org/fx"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">registerRoutes</span><span class="hljs-params">(lc fx.Lifecycle, handler *Handler)</span></span> {
    lc.Append(fx.Hook{
        OnStart: <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(ctx context.Context)</span> <span class="hljs-title">error</span></span> {
            http.Handle(<span class="hljs-string">"/user"</span>, handler)
            <span class="hljs-keyword">go</span> http.ListenAndServe(<span class="hljs-string">":8080"</span>, <span class="hljs-literal">nil</span>)
            <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>
        },
        OnStop: <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(ctx context.Context)</span> <span class="hljs-title">error</span></span> {
            log.Println(<span class="hljs-string">"shutting down server"</span>)
            <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>
        },
    })
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    app := fx.New(
        fx.Provide(NewUserRepository, NewUserService, NewHandler),
        fx.Invoke(registerRoutes),
    )

    app.Run() <span class="hljs-comment">// starts the app and manages lifecycle hooks</span>
}
</code></pre>
<p>Fx uses Dig under the hood for DI, but adds lifecycle hooks to manage startup and shutdown logic. You can register functions to run when the app starts or stops, making it easy to manage resources like HTTP servers, database connections, and so on. This can be particularly useful in microservices that require background workers, database connections, or scheduled jobs.</p>
<p>Fx also provides a more opinionated structure for your application, encouraging best practices and making it easier to reason about your code. The downside is that it introduces more complexity and a steeper learning curve compared to manual DI or even Dig alone.</p>
<p>Pros:</p>
<ul>
<li><p>Simplifies complex applications with lifecycle management.</p>
</li>
<li><p>Integrates DI with application startup and shutdown.</p>
</li>
<li><p>Good for microservices and enterprise-scale projects.</p>
</li>
</ul>
<p>Cons:</p>
<ul>
<li><p>Steeper learning curve than manual DI or Wire.</p>
</li>
<li><p>Locks you into the Fx framework.</p>
</li>
<li><p>Somewhat heavier than other solutions. May feel overkill for small apps.</p>
</li>
</ul>
<h3 id="heading-other-lightweight-di-helpers">Other Lightweight DI Helpers</h3>
<p>Besides Wire, Dig, and Fx, there are smaller tools like:</p>
<ul>
<li><p><a target="_blank" href="https://github.com/samber/do">do</a>: A minimalistic DI container that focuses on simplicity and ease of use. It provides basic functionality to register and resolve dependencies without much overhead.</p>
</li>
<li><p><a target="_blank" href="https://github.com/justinas/alice">alice</a>: A lightweight middleware chaining library that can help manage dependencies in HTTP handlers, though it's not a full DI framework.</p>
</li>
</ul>
<p>These libraries are less commonly used but can be useful in specific scenarios. They typically offer a middle ground between manual DI and full-fledged frameworks.</p>
<h2 id="heading-choosing-the-right-tool">Choosing the Right Tool</h2>
<p>A few considerations when deciding whether to adopt a DI library:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Factor</td><td>Recommendation</td></tr>
</thead>
<tbody>
<tr>
<td>Small project</td><td>Stick to manual DI. Explicit is simple and idiomatic.</td></tr>
<tr>
<td>Medium project with several services</td><td>Consider Wire for compile-time safety.</td></tr>
<tr>
<td>Large microservices</td><td>Dig and Fx can manage wiring and lifecycle.</td></tr>
<tr>
<td>Testing flexibility</td><td>Dig and Fx allow swapping implementations dynamically.</td></tr>
</tbody>
</table>
</div><p>Remember: <strong>manual DI is always valid</strong>. Libraries are optional tools to reduce boilerplate and improve maintainability in larger systems. They should not replace understanding the underlying pattern.</p>
<h3 id="heading-key-takeaways-1">Key Takeaways</h3>
<ul>
<li><p>DI frameworks can reduce wiring complexity, but manual DI is still idiomatic and often sufficient.</p>
</li>
<li><p>Wire: compile-time safety, explicit generated code.</p>
</li>
<li><p>Dig: runtime reflection, flexible wiring.</p>
</li>
<li><p>Fx: DI + app lifecycle, best for large services.</p>
</li>
<li><p>Other tools: lightweight helpers for specific use cases.</p>
</li>
</ul>
<p>By understanding these tools, you can scale your Go applications cleanly while keeping dependencies manageable, testable, and explicit.</p>
<h3 id="heading-exercise-for-the-reader-1">Exercise for the Reader</h3>
<p>Try integrating one of these DI libraries into the example application we built earlier (or all of them). Start with Wire to see how compile-time DI works, then experiment with Dig or Fx for more complex scenarios. Observe how the wiring code changes and consider the trade-offs in terms of complexity, readability, and maintainability. Consult the documentation for each library to understand its features and limitations. This hands-on experience will help you decide when and how to use DI frameworks in your own projects.</p>
<h2 id="heading-best-practices-and-takeaways">Best Practices and Takeaways</h2>
<p>We've now looked at dependency injection (DI) from multiple angles: the idiomatic manual approach, the challenges that arise at scale, and the libraries that can help. The next logical question is: how do you decide what's right for your project?</p>
<p>This section summarizes best practices that apply regardless of whether you stick with manual DI or adopt a framework. The goal is to help you make practical, informed choices.</p>
<h3 id="heading-prefer-explicit-dependencies">Prefer Explicit Dependencies</h3>
<p>The most important principle in Go is clarity. Whether you're writing a small service or wiring up a large application, make dependencies explicit.</p>
<ul>
<li><p>Pass dependencies through constructors, not hidden global variables.</p>
</li>
<li><p>Use interfaces to abstract behavior when testing or swapping implementations.</p>
</li>
<li><p>Avoid magic - readers should see how things are connected.</p>
</li>
</ul>
<p>Example of explicit constructor-based DI:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">NewOrderService</span><span class="hljs-params">(repo OrderRepository, logger Logger)</span> *<span class="hljs-title">OrderService</span></span> {
    <span class="hljs-keyword">return</span> &amp;OrderService{repo: repo, logger: logger}
}
</code></pre>
<p>Anyone reading this constructor immediately knows that <code>OrderService</code> depends on a repository and a logger.</p>
<h3 id="heading-start-simple-manual-di">Start Simple (Manual DI)</h3>
<p>For most Go projects, manual DI is enough. It keeps things simple, predictable, and easy to follow.</p>
<ul>
<li><p>In small to medium services, wiring by hand in <code>main.go</code> is rarely a bottleneck.</p>
</li>
<li><p>Explicit wiring doubles as documentation: you can glance at <code>main.go</code> to see how the app is assembled.</p>
</li>
<li><p>Adding a framework too early can add complexity without clear benefits.</p>
</li>
</ul>
<p>A useful rule of thumb: If your wiring fits comfortably in one screen, manual DI is probably the best choice.</p>
<h3 id="heading-use-frameworks-to-tame-complexity">Use Frameworks to Tame Complexity</h3>
<p>That said, frameworks exist for a reason. When your <code>main.go</code> turns into hundreds of lines of boilerplate, consider a DI tool.</p>
<ul>
<li><p>Wire: best if you want compile-time safety and explicit generated code.</p>
</li>
<li><p>Dig: best if you want runtime flexibility with minimal setup.</p>
</li>
<li><p>Fx: best if you want both DI and application lifecycle management.</p>
</li>
</ul>
<p>Think of these frameworks as productivity helpers, not as replacements for understanding DI. You should always understand how dependencies flow through your code, even if a library is wiring them for you.</p>
<h3 id="heading-keep-wiring-at-the-edges">Keep Wiring at the Edges</h3>
<p>A common best practice is to keep wiring separate from business logic.</p>
<ul>
<li><p>Business logic should not care about how dependencies are constructed.</p>
</li>
<li><p>Wiring should happen at the application entry point (<code>main.go</code> or an <code>initApp()</code> function).</p>
</li>
<li><p>This separation keeps your core code decoupled and testable.</p>
</li>
</ul>
<p>Example structure:</p>
<pre><code class="lang-bash">/cmd/app/main.go    &lt;-- all wiring here
/internal/service/  &lt;-- business logic
/internal/repo/     &lt;-- data access
</code></pre>
<p>This way, tests can bypass the wiring entirely and construct only what they need.</p>
<h3 id="heading-favor-interfaces-for-testability">Favor Interfaces for Testability</h3>
<p>Dependency injection shines when it comes to testing. To get the most out of it, depend on interfaces rather than concrete types.</p>
<p>For example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> UserRepository <span class="hljs-keyword">interface</span> {
    FindUser(id <span class="hljs-keyword">int</span>) <span class="hljs-keyword">string</span>
}

<span class="hljs-keyword">type</span> UserService <span class="hljs-keyword">struct</span> {
    repo UserRepository
}
</code></pre>
<p>In production, you can inject a real <code>DBUserRepository</code>. In tests, you can inject a <code>FakeUserRepository</code>. This makes testing fast, isolated, and easy.</p>
<h3 id="heading-avoid-over-engineering">Avoid Over-Engineering</h3>
<p>While interfaces are powerful, overusing them can hurt readability. A good heuristic in Go is:</p>
<ul>
<li><p>If there's only one implementation, you probably don't need an interface.</p>
</li>
<li><p>Add interfaces when you need to mock something or swap implementations.</p>
</li>
</ul>
<p>This keeps your codebase clean without unnecessary abstractions.</p>
<h3 id="heading-balance-verbosity-and-magic">Balance Verbosity and Magic</h3>
<p>Every DI strategy sits on a spectrum:</p>
<ul>
<li><p>Manual DI: maximum explicitness, but verbose at scale.</p>
</li>
<li><p>Dig/Fx: less verbose, but more hidden wiring.</p>
</li>
<li><p>Wire: middle ground: generated code is explicit, but you don’t write it by hand.</p>
</li>
</ul>
<p>There's no one-size-fits-all answer. The right choice depends on your team's size, project complexity, and tolerance for boilerplate.</p>
<h3 id="heading-adopt-incrementally">Adopt Incrementally</h3>
<p>You don't need to commit to a DI framework from day one. Many teams:</p>
<ul>
<li><p>Start with manual DI.</p>
</li>
<li><p>As the project grows, refactor to Wire for compile-time safety.</p>
</li>
<li><p>If the project evolves into a complex service with many modules, adopt Fx for lifecycle management.</p>
</li>
</ul>
<p>This incremental approach ensures you never add more complexity than you need.</p>
<h3 id="heading-document-your-wiring">Document Your Wiring</h3>
<p>Whether manual or framework-based, document how dependencies are wired.</p>
<ul>
<li><p>In manual DI, <code>main.go</code> often serves as self-documenting code.</p>
</li>
<li><p>With frameworks, add comments or diagrams explaining the flow.</p>
</li>
<li><p>New contributors should be able to understand the structure without guesswork.</p>
</li>
</ul>
<h3 id="heading-key-takeaways-2">Key Takeaways</h3>
<ul>
<li><p>Be explicit: make dependencies visible and testable.</p>
</li>
<li><p>Start simple: manual DI works well in most projects.</p>
</li>
<li><p>Use frameworks only when needed: Wire, Dig, and Fx can only help manage complexity if <em>there is</em> complexity.</p>
</li>
<li><p>Keep wiring at the edges: business logic should stay clean and decoupled.</p>
</li>
<li><p>Follow Go's philosophy: prefer clarity and simplicity over cleverness.</p>
</li>
</ul>
<p>By following these best practices, you'll be able to manage dependencies effectively in Go - whether you're writing a tiny CLI tool or a large-scale microservice.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Dependency injection in Go doesn't need to be mysterious or complicated. At its core, it's simply about passing dependencies into your code rather than creating them inside it. This small shift in design makes your applications easier to test, more modular, and more maintainable.</p>
<p>We've seen the three main approaches:</p>
<ul>
<li><p>Manual DI: the idiomatic baseline in Go. Explicit, clear, and great for most projects.</p>
</li>
<li><p>Compile-time tools like Wire: reduce boilerplate while keeping wiring explicit.</p>
</li>
<li><p>Runtime frameworks like Dig and Fx: powerful for large applications that need flexibility and lifecycle management.</p>
</li>
</ul>
<p>There is no single "right" choice. The best approach depends on the size and complexity of your project, your team's preferences, and how much wiring you're willing to manage by hand.</p>
<p>If you take one thing away from this guide, let it be this: <strong>start simple with manual DI, and only reach for tools when the cost of wiring by hand outweighs the benefits of explicitness</strong>.</p>
<p>By understanding the trade-offs and following best practices, you'll be well equipped to structure Go applications that are clear, testable, and scalable, whether you're writing a tiny web service or a full-blown distributed system.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Refactor to Configurable Dependency in 5 Steps ]]>
                </title>
                <description>
                    <![CDATA[ By Bertil Muth Configurable Dependency, also known as Dependency Injection, is a pattern that enables you to switch dependencies of your application. The term was coined by Alistair Cockburn. Say your application has a GUI. But your administrator wan... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/refactoring-to-configurable-dependency-in-5-steps/</link>
                <guid isPermaLink="false">66d45dea4a7504b7409c335b</guid>
                
                    <category>
                        <![CDATA[ dependency injection ]]>
                    </category>
                
                    <category>
                        <![CDATA[ refactoring ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 19 Aug 2022 20:42:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/08/diana-polekhina-ONuLIzB0UtA-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Bertil Muth</p>
<p>Configurable Dependency, also known as Dependency Injection, is a pattern that enables you to switch dependencies of your application. The <a target="_blank" href="https://web.archive.org/web/20170624023207/http://alistair.cockburn.us/Configurable+Dependency">term</a> was coined by Alistair Cockburn.</p>
<p>Say your application has a GUI. But your administrator wants to use certain functions via the console. Or your production code calls an external service. But your tests shouldn’t call the service, since it doesn’t provide reliable results. Or the service isn’t always available.</p>
<p>Here’s where a Configurable Dependency is helpful. Depending on context, you use one dependency or the other.</p>
<p>A lot of articles attempt to explain the pattern. But they embed it in a broader context, like ports and adapters architecture. That makes understanding harder than necessary. I know, I’ve written such articles myself.</p>
<p>On top of that, many articles focus on greenfield applications. But most of us have to maintain applications that already exist.</p>
<p>Let’s start with a simple class that has a hard-wired dependency. Then we'll refactor it to a class that has a Configurable Dependency. </p>
<p>The example is trivial, but the refactoring steps are generally applicable to your own application if you’re in a similar situation.</p>
<p>I’ll refer to an example <a target="_blank" href="https://github.com/bertilmuth/configurable-dependency">GitHub project</a> in the article. It shows the steps to perform, in its commit history. At the end of the article, there are appendices for IntelliJ IDEA and Eclipse. They show how to do the refactoring steps in your IDE.</p>
<h1 id="heading-the-calculator-example">The Calculator Example</h1>
<p>Say you have a class called <code>Calculator</code>. It’s the equivalent of “business logic”. At the end of each calculation, it prints the result to the screen. In a real world application, it might save something to a database instead.</p>
<p><a target="_blank" href="https://github.com/bertilmuth/configurable-dependency/blob/3d8540dd9566cb48f29902b9c9e10292cf8f7560/src/main/java/example/Calculator.java">Here</a>’s the code:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> example;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Calculator</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Calculator</span><span class="hljs-params">()</span></span>{
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">long</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">long</span> one, <span class="hljs-keyword">long</span> two)</span> </span>{
        <span class="hljs-keyword">long</span> result = one + two;
        printResult(result);
        <span class="hljs-keyword">return</span> result;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">long</span> <span class="hljs-title">sub</span><span class="hljs-params">(<span class="hljs-keyword">long</span> one, <span class="hljs-keyword">long</span> two)</span> </span>{
        <span class="hljs-keyword">long</span> result = one - two;
        printResult(result);
        <span class="hljs-keyword">return</span> result;
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">printResult</span><span class="hljs-params">(<span class="hljs-keyword">long</span> result)</span> </span>{
        System.out.println(<span class="hljs-string">"The result is: "</span> + result);
    }
}
</code></pre>
<p>Now if you want to test that class, your <a target="_blank" href="https://github.com/bertilmuth/configurable-dependency/blob/3d8540dd9566cb48f29902b9c9e10292cf8f7560/src/test/java/example/CalculatorTest.java">test code</a> may look like this:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> example;

<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.junit.jupiter.api.Assertions.*;
<span class="hljs-keyword">import</span> org.junit.jupiter.api.*;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CalculatorTest</span> </span>{
    <span class="hljs-keyword">private</span> Calculator calculator;

    <span class="hljs-meta">@BeforeEach</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
        calculator = <span class="hljs-keyword">new</span> Calculator();
    }

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">addsToNumbers</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">long</span> result = calculator.add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
        assertEquals(<span class="hljs-number">3</span>, result);
    }

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">subtractsToNumbers</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">long</span> result = calculator.sub(<span class="hljs-number">5</span>, <span class="hljs-number">1</span>);
        assertEquals(<span class="hljs-number">4</span>, result);
    }
}
</code></pre>
<p>Every time you run your test, it prints the results to the screen. That’s unnecessary. It slows your tests down.</p>
<p>With dependency injection, you can still assert the result in the test. But you avoid printing the result to the screen (or saving the result to the database, the file system, or somewhere else).</p>
<h2 id="heading-step-1-move-dependency-creation-to-the-constructor">Step 1: Move Dependency Creation to the Constructor</h2>
<p>Find out where an instance of the dependent class is created. Move creation to the constructor by assigning the instance to a field. Use the field throughout the class, so that only the constructor creates the dependency.</p>
<p>The example code is a bit different. The dependency is a static one, <code>System.out</code>. But as described above, the refactored code assigns it to the <code>printer</code> field in the constructor.</p>
<p>So the <code>Calculator</code> class now looks like <a target="_blank" href="https://github.com/bertilmuth/configurable-dependency/blob/43ba441138edafdbca2f7f4a100f5e5b528235a2/src/main/java/example/Calculator.java">this</a>:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> example;

<span class="hljs-keyword">import</span> java.io.PrintStream;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Calculator</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> PrintStream printer;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Calculator</span><span class="hljs-params">()</span></span>{
        printer = System.out;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">long</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">long</span> one, <span class="hljs-keyword">long</span> two)</span> </span>{
        <span class="hljs-keyword">long</span> result = one + two;
        printResult(result);
        <span class="hljs-keyword">return</span> result;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">long</span> <span class="hljs-title">sub</span><span class="hljs-params">(<span class="hljs-keyword">long</span> one, <span class="hljs-keyword">long</span> two)</span> </span>{
        <span class="hljs-keyword">long</span> result = one - two;
        printResult(result);
        <span class="hljs-keyword">return</span> result;
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">printResult</span><span class="hljs-params">(<span class="hljs-keyword">long</span> result)</span> </span>{
        printer.println(<span class="hljs-string">"The result is: "</span> + result);
    }
}
</code></pre>
<p>Run the test. It still needs to pass.</p>
<h2 id="heading-step-2-pass-the-dependency-as-a-constructor-argument">Step 2: Pass the Dependency as a Constructor Argument</h2>
<p>Pass the instance as a constructor argument, instead of creating it in the constructor. <a target="_blank" href="https://github.com/bertilmuth/configurable-dependency/blob/411cb1650ddfd209b12d0ebc9007fcd1f857d280/src/main/java/example/Calculator.java">Here</a>’s the refactored example code:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> example;

<span class="hljs-keyword">import</span> java.io.PrintStream;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Calculator</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> PrintStream printer;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Calculator</span><span class="hljs-params">(PrintStream printer)</span></span>{
        <span class="hljs-keyword">this</span>.printer = printer;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">long</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">long</span> one, <span class="hljs-keyword">long</span> two)</span> </span>{
        <span class="hljs-keyword">long</span> result = one + two;
        printResult(result);
        <span class="hljs-keyword">return</span> result;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">long</span> <span class="hljs-title">sub</span><span class="hljs-params">(<span class="hljs-keyword">long</span> one, <span class="hljs-keyword">long</span> two)</span> </span>{
        <span class="hljs-keyword">long</span> result = one - two;
        printResult(result);
        <span class="hljs-keyword">return</span> result;
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">printResult</span><span class="hljs-params">(<span class="hljs-keyword">long</span> result)</span> </span>{
        printer.println(<span class="hljs-string">"The result is: "</span> + result);
    }
}
</code></pre>
<p>For this class to work, you need to adapt each line of code that creates a <code>Calculator</code> object to pass in the dependency. So the line to create the <code>Calculator</code> in <a target="_blank" href="https://github.com/bertilmuth/configurable-dependency/blob/411cb1650ddfd209b12d0ebc9007fcd1f857d280/src/test/java/example/CalculatorTest.java">CalculatorTest</a> now looks like this:</p>
<p><code>calculator = new Calculator(System.out);</code></p>
<p>Run the test. It still needs to pass.</p>
<h2 id="heading-step-3-create-an-interface-and-implementation">Step 3: Create an Interface and Implementation</h2>
<p>Create an <a target="_blank" href="https://github.com/bertilmuth/configurable-dependency/blob/d453d47d297eed94108f4b136e467fc66502fe84/src/main/java/example/PrintStream.java">interface</a> with the exact same name as the class name of the dependency. Place it in the same package. Put the method in it that the business logic calls.</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> example;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">PrintStream</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">println</span><span class="hljs-params">(String text)</span></span>;
}
</code></pre>
<p>In the <a target="_blank" href="https://github.com/bertilmuth/configurable-dependency/blob/d453d47d297eed94108f4b136e467fc66502fe84/src/main/java/example/Calculator.java">Calculator</a> class, remove the import statement of the dependency, <code>java.io.PrintStream</code>, to use the new interface instead.</p>
<p>Here’s one implementation of the interface. <a target="_blank" href="https://github.com/bertilmuth/configurable-dependency/blob/d453d47d297eed94108f4b136e467fc66502fe84/src/main/java/example/ConsolePrinter.java">ConsolePrinter</a> contains the original functionality that prints to a screen.</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> example;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConsolePrinter</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">PrintStream</span></span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">println</span><span class="hljs-params">(String text)</span> </span>{
        System.out.println(text);
    }
}
</code></pre>
<p>In the <a target="_blank" href="https://github.com/bertilmuth/configurable-dependency/blob/d453d47d297eed94108f4b136e467fc66502fe84/src/test/java/example/CalculatorTest.java">test class</a>, pass in the <code>ConsolePrinter</code>. Run the test. It still needs to pass, and print the results to the screen:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> example;

<span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> org.junit.jupiter.api.Assertions.*;
<span class="hljs-keyword">import</span> org.junit.jupiter.api.*;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CalculatorTest</span> </span>{
    <span class="hljs-keyword">private</span> Calculator calculator;

    <span class="hljs-meta">@BeforeEach</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">setup</span><span class="hljs-params">()</span> </span>{
        calculator = <span class="hljs-keyword">new</span> Calculator(<span class="hljs-keyword">new</span> ConsolePrinter());
    }

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">addsToNumbers</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">long</span> result = calculator.add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
        assertEquals(<span class="hljs-number">3</span>, result);
    }

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">subtractsToNumbers</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">long</span> result = calculator.sub(<span class="hljs-number">5</span>, <span class="hljs-number">1</span>);
        assertEquals(<span class="hljs-number">4</span>, result);
    }
}
</code></pre>
<h2 id="heading-step-4-rename-and-clean-up">Step 4: Rename and Clean Up</h2>
<p>This is an optional step. You can decide to rename the interface, to give it a more meaningful name. For example, rename <code>PrintStream</code> to <a target="_blank" href="https://github.com/bertilmuth/configurable-dependency/blob/d453d47d297eed94108f4b136e467fc66502fe84/src/test/java/example/CalculatorTest.java">Printer</a>. </p>
<p>You can also decide to move the class to a different package and rename its method(s).</p>
<p>Run the test. It still needs to pass.</p>
<h2 id="heading-step-5-configure-the-dependency">Step 5: Configure the Dependency</h2>
<p>Create <a target="_blank" href="https://github.com/bertilmuth/configurable-dependency/blob/66a4aadbaad42616661357bc0ba9f5aaa6f5d846/src/main/java/example/IdlePrinter.java">another implementation</a> that ignores the text argument, for testing purposes:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> example;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IdlePrinter</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Printer</span></span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">println</span><span class="hljs-params">(String text)</span> </span>{
        <span class="hljs-comment">// This is empty, because we don't want to print in tests.</span>
    }
}
</code></pre>
<p>Now, you can change a single line of the CalculatorTest to turn off printing:</p>
<p><code>calculator = new Calculator(new IdlePrinter());</code></p>
<p>Since Java 8, you don’t even need <code>IdlePrinter</code>. Pass in a Lambda function instead:</p>
<p><code>calculator = new Calculator(text -&gt; {});</code></p>
<h2 id="heading-congratulations">Congratulations!</h2>
<p>You have refactored to a Configurable Dependency.</p>
<p>Have a look at the <a target="_blank" href="https://github.com/bertilmuth/configurable-dependency">GitHub project</a> commit history to see the changes in code that I performed.</p>
<p>If you have any questions, leave a comment or contact me.</p>
<p>Twitter: <a target="_blank" href="https://twitter.com/BertilMuth">https://twitter.com/BertilMuth</a></p>
<p>LinkedIn: <a target="_blank" href="https://www.linkedin.com/in/bertilmuth/">https://www.linkedin.com/in/bertilmuth/</a></p>
<p>The following appendices explain the concrete refactoring steps in IntelliJ IDEA and Eclipse.</p>
<h1 id="heading-appendix-a-how-to-refactor-in-intellij-idea">Appendix A — How to refactor in IntelliJ IDEA</h1>
<h2 id="heading-intellij-step-1-move-dependency-creation-to-the-constructor">IntelliJ Step 1: Move Dependency Creation to the Constructor</h2>
<p>Open the <code>Calculator</code> class. Locate <code>System.out</code>. Right click, select <code>Refactor &gt; Introduce Field</code>. Select <code>initialize in: constructor</code>. Name the field <code>printer</code>. Hit Return.</p>
<h2 id="heading-intellij-step-2-pass-the-dependency-as-a-constructor-argument">IntelliJ Step 2: Pass the Dependency as a Constructor Argument</h2>
<p>Set the cursor into the constructor, <code>Calculator()</code>. Mark the access to the dependency, <code>System.out</code>. Right click, select <code>Refactor &gt; Introduce Parameter</code>. Name the field <code>printer</code>. Hit Return.</p>
<h2 id="heading-intellij-step-3-create-an-interface-and-implementation">IntelliJ Step 3: Create an interface and Implementation</h2>
<p>Create the interface and implementation in the same package:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> example;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">PrintStream</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">println</span><span class="hljs-params">(String text)</span></span>;
}
</code></pre>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> example;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConsolePrinter</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">PrintStream</span></span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">println</span><span class="hljs-params">(String text)</span> </span>{
        System.out.println(text);
    }
}
</code></pre>
<p>Go to the business logic class <code>Calculator</code> and remove the import statement <code>import java.io.PrintStream;</code>. Save the file.</p>
<p>In the test class <code>CalculatorTest</code>, use the new implementation class.</p>
<p>Change this:</p>
<p><code>calculator = new Calculator(System.out);</code></p>
<p>to this:</p>
<p><code>calculator = new Calculator(new ConsolePrinter());</code></p>
<p>Save the file. Run the test and check if it still passes.</p>
<h2 id="heading-intellij-step-4-rename-and-clean-up">IntelliJ Step 4: Rename and Clean Up</h2>
<p>Go to the interface <code>PrintStream</code>. Right click on <code>PrintStream</code> and select <code>Refactor &gt; Rename</code>. Enter <code>Printer</code> and press Return. Run the test and check if it still passes.</p>
<h2 id="heading-intellij-step-5-configure-the-dependency">IntelliJ Step 5: Configure the Dependency</h2>
<p>Create another implementation that ignores the text argument, for testing purposes:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> example;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IdlePrinter</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Printer</span></span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">println</span><span class="hljs-params">(String text)</span> </span>{
        <span class="hljs-comment">// This is empty, because we don't want to print in tests.</span>
    }
}
</code></pre>
<p>Go to <code>CalculatorTest</code> and change this:</p>
<p><code>calculator = new Calculator(new ConsolePrinter());</code></p>
<p>to this:</p>
<p><code>calculator = new Calculator(new IdlePrinter());</code></p>
<p>Save the file. Run the test and check if it still passes.</p>
<p>The text output should now be off. Well done.</p>
<h1 id="heading-appendix-b-how-to-refactor-in-eclipse">Appendix B — How to Refactor in Eclipse</h1>
<h2 id="heading-eclipse-step-1-move-dependency-creation-to-the-constructor">Eclipse Step 1: Move Dependency Creation to the Constructor</h2>
<p>Open the <code>Calculator</code> class. Locate <code>System.out</code>. Right click, select <code>Refactor &gt; Extract Local Variable</code>. Click <code>OK</code>. </p>
<p>Mark the newly created local variable <code>out</code>. Right click, select <code>Refactor &gt; Convert Local Variable to Field</code>. Name the variable <code>printer</code>. Choose <code>Initialize in Class Constructors</code>. Check <code>Declare field as ‘final’</code>. Hit <code>OK</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/grafik-13.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Run the test and check if it still passes.</p>
<h2 id="heading-eclipse-step-2-pass-the-dependency-as-a-constructor-argument">Eclipse Step 2: Pass the Dependency as a Constructor Argument</h2>
<p>Set the cursor into the constructor, <code>Calculator()</code>. Mark the access to the dependency, <code>System.out</code>, and copy it to the clipboard (CTRL-C).</p>
<p>Right click, select <code>Refactor &gt; Change Method Signature</code>. Click <code>Add</code>. Type <code>PrintStream</code> under <code>Type</code>, <code>printer</code> under <code>Name</code>, and paste <code>System.out</code> under <code>Default value.</code> Click <code>OK</code> and <code>Continue.</code></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/grafik-14.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Change the constructor to look like this:</p>
<p><code>public Calculator(PrintStream printer){</code><br> <code>this.printer = printer;</code><br> <code>}</code></p>
<p>Save the file. Run the test and check if it still passes.</p>
<h2 id="heading-eclipse-step-3-create-an-interface-and-implementation">Eclipse Step 3: Create an Interface and Implementation</h2>
<p>Create the interface and implementation in the same package:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> example;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">PrintStream</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">println</span><span class="hljs-params">(String text)</span></span>;
}
</code></pre>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> example;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConsolePrinter</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">PrintStream</span></span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">println</span><span class="hljs-params">(String text)</span> </span>{
        System.out.println(text);
    }
}
</code></pre>
<p>Go to the business logic class <code>Calculator</code> and remove the import statement <code>import java.io.PrintStream;</code>. Save the file.</p>
<p>In the test class <code>CalculatorTest</code>, use the new implementation class.</p>
<p>Change this:</p>
<p><code>calculator = new Calculator(System.out);</code></p>
<p>to this:</p>
<p><code>calculator = new Calculator(new ConsolePrinter());</code></p>
<p>Save the file. Run the test and check if it still passes.</p>
<h2 id="heading-eclipse-step-4-rename-and-clean-up">Eclipse Step 4: Rename and Clean Up</h2>
<p>Go to the interface <code>PrintStream</code>. Right click on <code>PrintStream</code> and select <code>Refactor &gt; Rename</code>. Enter <code>Printer</code> and press Return. Run the test and check if it still passes.</p>
<h2 id="heading-eclipse-step-5-configure-the-dependency">Eclipse Step 5: Configure the Dependency</h2>
<p>Create another implementation that ignores the text argument, for testing purposes:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> example;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IdlePrinter</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Printer</span></span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">println</span><span class="hljs-params">(String text)</span> </span>{
        <span class="hljs-comment">// This is empty, because we don't want to print in tests.</span>
    }
}
</code></pre>
<p>Go to <code>CalculatorTest</code> and change this:</p>
<p><code>calculator = new Calculator(new ConsolePrinter());</code></p>
<p>to this:</p>
<p><code>calculator = new Calculator(new IdlePrinter());</code></p>
<p>Save the file. Run the test and check if it still passes.</p>
<p>The text output should now be off. Well done.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Angular Dependency Injection Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ What is Dependency Injection? Motivation Dependency Injection is often more simply referred to as DI. The paradigm exists throughout Angular. It keeps code flexible, testable, and mutable. Classes can inherit external logic without knowing how to cre... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/angular-dependency-injection/</link>
                <guid isPermaLink="false">66c344ab0fa3812cdd5ea9a5</guid>
                
                    <category>
                        <![CDATA[ Angular ]]>
                    </category>
                
                    <category>
                        <![CDATA[ dependency injection ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 07 Feb 2020 23:41:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9cb0740569d1a4ca339e.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h1 id="heading-what-is-dependency-injection"><strong>What is Dependency Injection?</strong></h1>
<h4 id="heading-motivation"><strong>Motivation</strong></h4>
<p>Dependency Injection is often more simply referred to as DI. The paradigm exists throughout Angular. It keeps code flexible, testable, and mutable. Classes can inherit external logic without knowing how to create it. Any consumers of those classes also do not need to know anything.</p>
<p>DI saves classes and consumers alike from having to know more than necessary. Yet the code is as modular as it was before thanks to the mechanisms supporting DI in Angular.</p>
<p>Services are a key benefactor of DI. They rely on the paradigm for <em>injection</em> into various consumers. Those consumers can then take advantage of that service provides and/or forward it elsewhere.</p>
<p>Service are not alone. Directives, pipes, components, and so on: every schematic in Angular benefits from DI in some way or another.</p>
<h2 id="heading-injectors">Injectors</h2>
<p>Injectors are data structures that store instructions detailing where and how services form. They act as intermediaries within the Angular DI system.</p>
<p>Module, directive, and component classes contain metadata specific to injectors. A new injector instance accompanies every one of these classes. In this way, the application tree mirrors its hierarchy of injectors.</p>
<p>The <code>providers: []</code> metadata accepts services that then register with the class’ injector. This provider field adds the instructions necessary for an injector to function. A class (assuming it has dependencies) instantiates a service by taking on its class as its data type. The injector aligns this type a creates an instance of that service on the class’ behalf.</p>
<p>Of course, the class can only instantiate what the injector has instructions for. If the class’ own injector does not have the service registered, then it queries its parent. So on and so forth until either reaching an injector with the service or the application root.</p>
<p>Services can register at any injector within the application. Services go in the <code>providers: []</code> metadata field of class modules, directives, or components. The class’ children can instantiate a service registered in the class’ injector. Child injectors fallback on parent injectors after all.</p>
<h2 id="heading-dependency-injection">Dependency Injection</h2>
<p>Take a look at the skeletons for each class: service, module, directive, and component.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// service</span>

<span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;

<span class="hljs-meta">@Injectable</span>({
  providedIn: <span class="hljs-comment">/* injector goes here */</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> TemplateService {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) { }
}
</code></pre>
<pre><code class="lang-typescript"><span class="hljs-comment">// module</span>

<span class="hljs-keyword">import</span> { NgModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { CommonModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/common'</span>;

<span class="hljs-meta">@NgModule</span>({
  imports: [
    CommonModule
  ],
  declarations: [],
  providers: [ <span class="hljs-comment">/* services go here */</span> ]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> TemplateModule { }
</code></pre>
<pre><code class="lang-typescript"><span class="hljs-comment">// directive</span>

<span class="hljs-keyword">import</span> { Directive } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;

<span class="hljs-meta">@Directive</span>({
  selector: <span class="hljs-string">'[appTemplate]'</span>,
  providers: [ <span class="hljs-comment">/* services go here */</span> ]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> TemplateDirective {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) { }
}
</code></pre>
<pre><code class="lang-typescript"><span class="hljs-comment">//component</span>

<span class="hljs-keyword">import</span> { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'app-template'</span>,
  templateUrl: <span class="hljs-string">'./template.component.html'</span>,
  styleUrls: [<span class="hljs-string">'./template.component.css'</span>],
  providers: [ <span class="hljs-comment">/* services go here */</span> ]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> TemplateComponent {
  <span class="hljs-comment">// class logic ...</span>
}
</code></pre>
<p>Each skeleton can register services to an injector. In fact, TemplateService <em>is</em> a service. As of Angular 6, services can now register with injectors using <code>@Injectable</code> metadata.</p>
<h5 id="heading-in-any-case"><strong>In Any Case</strong></h5>
<p>Notice the <code>providedIn: string</code> (<code>@Injectable</code>) and <code>providers: []</code> (<code>@Directive</code>, <code>@Componet</code> and <code>@Module</code>) metadata. They tell injectors where and how to create a service. Otherwise, injectors would not know how to instantiate.</p>
<p>What if a service has dependencies? Where would the results go? Providers answers those question so that injectors can instantiate properly.</p>
<p>Injectors form the backbone of the DI framework. They store instructions to instantiate services so consumers do not have to. They receive service instances without needing to know anything about the source dependency!</p>
<p>I should also note that other schematics without injectors can still utilize dependency injection. They cannot register additional services but they can still instantiate from injectors.</p>
<h2 id="heading-service">Service</h2>
<p>The <code>providedIn: string</code> metadata of <code>@Injectable</code> specifies which injector to register with. Using this method, and depending on if the service gets used, the service may or may not register with the injector. Angular calls this <em>tree-shaking</em>.</p>
<p>By default the value is set to <code>‘root’</code>. This translates to the root injector of the application. Basically, setting the field to <code>‘root’</code> makes the service available anywhere.</p>
<h5 id="heading-quick-note"><strong>Quick Note</strong></h5>
<p>As previously mentioned, child injectors fallback on their parents. This fallback strategy ensures parents do not have to re-register for every injector. Refer to this article on <a target="_blank" href="https://guide.freecodecamp.org/angular/services-and-injectors">Services and Injectors</a> for an illustration of this concept.</p>
<p>Registered services are <em>singletons</em>. Meaning, the instructions to instantiate the service exists on only one injector. This assumes it has not been explicitly registered elsewhere.</p>
<h2 id="heading-module-directive-and-component">Module, Directive, and Component</h2>
<p>Modules and components each have their own injector instance. This is evident given the <code>providers: []</code> metadata field. This field takes an array of services and registers them with the injector of the module or component class. This approach happens in the <code>@NgModule</code>, <code>@Directive</code>, or <code>@Component</code> decorators.</p>
<p>This strategy omits <em>tree-shaking</em>, or the optional removal of unused services from injectors. Service instances live on their injectors for the life of the module or component.</p>
<h2 id="heading-instantiating-references">Instantiating References</h2>
<p>References to the DOM can instantiate from any class. Keep in mind that references are still services. They differ from traditional services in representing the state of something else. These services include functions to interact with their reference.</p>
<p>Directives are in constant need of DOM references. Directives perform mutations on their host elements through these references. See the following example. The directive’s injector instantiates a reference of the host element into the class’ constructor.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// directives/highlight.directive.ts</span>

<span class="hljs-keyword">import</span> { Directive, ElementRef, Renderer2, Input } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;

<span class="hljs-meta">@Directive</span>({
  selector: <span class="hljs-string">'[appHighlight]'</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> HighlightDirective {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params">
    <span class="hljs-keyword">private</span> renderer: Renderer2,
    <span class="hljs-keyword">private</span> host: ElementRef
  </span>) { }

  <span class="hljs-meta">@Input</span>() set appHighlight (color: <span class="hljs-built_in">string</span>) {
    <span class="hljs-built_in">this</span>.renderer.setStyle(<span class="hljs-built_in">this</span>.host.nativeElement, <span class="hljs-string">'background-color'</span>, color);
  }
}
</code></pre>
<pre><code class="lang-html">// app.component.html

<span class="hljs-tag">&lt;<span class="hljs-name">p</span> [<span class="hljs-attr">appHighlight</span>]=<span class="hljs-string">"'yellow'"</span>&gt;</span>Highlighted Text!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p><code>Renderer2</code> also gets instantiated. Which injector do these services come from? Well, each service’s source code comes from <code>@angular/core</code>. These services must then register with the application’s root injector.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { BrowserModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/platform-browser'</span>;
<span class="hljs-keyword">import</span> { NgModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { AppComponent } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.component'</span>;
<span class="hljs-keyword">import</span> { HighlightDirective } <span class="hljs-keyword">from</span> <span class="hljs-string">'./directives/highlight.directive'</span>;

<span class="hljs-meta">@NgModule</span>({
  declarations: [
    AppComponent,
    HighlightDirective
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [
    AppComponent
  ]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule { }
</code></pre>
<p>An empty providers array!? Not to fear. Angular registers many services with the root injector automatically. This includes <code>ElementRef</code> and <code>Renderer2</code>. In this example, we are managing the host element through its interface stemming from the instantiation of <code>ElementRef</code>. <code>Renderer2</code> lets us update the DOM through Angular’s view model.</p>
<p>You can read more about views from <a target="_blank" href="https://guide.freecodecamp.org/angular/views">this article</a>. They are the preferred method for DOM/view updates in Angular applications.</p>
<p>It is important recognize the role that injectors play in the above example. By declaring variable types in the constructor, the class obtains valuable services. Each parameter’s data type maps to a set of instructions within the injector. If the injector has that type, it returns an instance of said type.</p>
<h2 id="heading-instantiating-services">Instantiating Services</h2>
<p>The <a target="_blank" href="https://guide.freecodecamp.org/angular/services-and-injectors">Services and Injectors</a> article explains this section to an extent. Though, this section rehashes the previous section or the most part. Services will often provide references to something else. They may just as well provide an interface extending a class’ capabilities.</p>
<p>The next example will define a logging service that gets added to a component’s injector via its <code>providers: []</code> metadata.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// services/logger.service.ts</span>

<span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> LoggerService {
  callStack: <span class="hljs-built_in">string</span>[] = [];

  addLog(message: <span class="hljs-built_in">string</span>): <span class="hljs-built_in">void</span> {
    <span class="hljs-built_in">this</span>.callStack = [message].concat(<span class="hljs-built_in">this</span>.callStack);
    <span class="hljs-built_in">this</span>.printHead();
  }

  clear(): <span class="hljs-built_in">void</span> {
    <span class="hljs-built_in">this</span>.printLog();
    <span class="hljs-built_in">this</span>.callStack = [];
    <span class="hljs-built_in">console</span>.log(“DELETED LOG”);
  }

  <span class="hljs-keyword">private</span> printHead(): <span class="hljs-built_in">void</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.callStack[<span class="hljs-number">0</span>] || <span class="hljs-literal">null</span>);
  }

  <span class="hljs-keyword">private</span> printLog(): <span class="hljs-built_in">void</span> {
    <span class="hljs-built_in">this</span>.callStack.reverse().forEach(<span class="hljs-function">(<span class="hljs-params">log</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(message));
  }
}
</code></pre>
<pre><code class="lang-typescript"><span class="hljs-comment">// app.component.ts</span>

<span class="hljs-keyword">import</span> { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { LoggerService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./services/logger.service'</span>;

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'app-root'</span>,
  templateUrl: <span class="hljs-string">'./app.component.html'</span>,
  providers: [LoggerService]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppComponent {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> logger: LoggerService</span>) { }

  logMessage(event: <span class="hljs-built_in">any</span>, message: <span class="hljs-built_in">string</span>): <span class="hljs-built_in">void</span> {
    event.preventDefault();
    <span class="hljs-built_in">this</span>.logger.addLog(<span class="hljs-string">`Message: <span class="hljs-subst">${message}</span>`</span>);
  }

  clearLog(): <span class="hljs-built_in">void</span> {
    <span class="hljs-built_in">this</span>.logger.clear();
  }
}
</code></pre>
<pre><code class="lang-html">// app.component.html

<span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Log Example<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">form</span> (<span class="hljs-attr">submit</span>)=<span class="hljs-string">"logMessage($event, userInput.value)"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> #<span class="hljs-attr">userInput</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Type a message..."</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>SUBMIT<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Delete Logged Messages<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> (<span class="hljs-attr">click</span>)=<span class="hljs-string">"clearLog()"</span>&gt;</span>CLEAR<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>Focus on the AppComponent constructor and metadata. The component injector receives instructions from the provider’s metadata field containing LoggerService. The injector then knows what to instantiate LoggerService from requested in the constructor.</p>
<p>The constructor parameter <code>loggerService</code> has the type <code>LoggerService</code> which the injector recognizes. The injector follows through with the instantiation as mentioned.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Dependency injection (DI) is a paradigm. The way it works in Angular is through a hierarchy of injectors. A class receives its resources without having to create or know about them. Injectors receive instruction and instantiate a service depending on which one was requested.</p>
<p>DI shows up a lot in Angular. The official Angular documentation explains why the paradigm is so prevalent. They also go on to describe the numerous use-cases for DI in Angular way beyond what was discussed in this article. Check it out by clicking below!</p>
<h2 id="heading-more-on-dependency-injection">More on dependency injection:</h2>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/angular-dependency-injection-in-detail-8b6822d6457c/">Intro to Angular dependency injection</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/angular-dependency-injection/freecodecamp.org/news/a-quick-intro-to-dependency-injection-what-it-is-and-when-to-use-it-7578c84fa88f/">Quick intro to dependency injection</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Angular Services and Dependency Injection Explained ]]>
                </title>
                <description>
                    <![CDATA[ Services and Injectors Components are responsible for the data that renders into the template. Having external services to draw upon can simplify this responsibility. Plus, encapsulating extraneous is much easier to maintain. Delegating too many resp... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/angular-services-and-dependency-injection-explained/</link>
                <guid isPermaLink="false">66c344c10bafa8455505c67d</guid>
                
                    <category>
                        <![CDATA[ Angular ]]>
                    </category>
                
                    <category>
                        <![CDATA[ dependency injection ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 28 Jan 2020 00:00:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9d5e740569d1a4ca3765.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h1 id="heading-services-and-injectors"><strong>Services and Injectors</strong></h1>
<p>Components are responsible for the data that renders into the template. Having external <em>services</em> to draw upon can simplify this responsibility. Plus, encapsulating extraneous is much easier to maintain.</p>
<p>Delegating too many responsibilities onto a single component can complicate the component class. And what if these responsibilities applied to several components? Copying and pasting such logic is extremely poor practice. Any future changes to the logic would be harder to implement and test.</p>
<p>Angular meant to curb this issue with services and dependency injection. Both concepts work together to provide <em>modular</em> functionality.</p>
<p>Components do not need to provide any extraneous information either. A services imports what it needs to function on behalf of the components it <em>services</em>. The components only need to instantiate the service. From there they <em>service</em> their own needs with the instantiated service instance.</p>
<p>As for testing and future modification, all the logic is in one place. The service instantiates from its source. Tests and modifications to the source apply anywhere the service is injected.</p>
<h2 id="heading-introduction-to-services">Introduction to Services</h2>
<p>A service is a type of <em>schematic</em> available in Angular. It is generatable by the command-line interface (CLI): <code>ng generate service [name-of-service]</code>. Replace <code>[name-of-service]</code> with a preferable name. The CLI command yields the following.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;

<span class="hljs-meta">@Injectable</span>({
  providedIn: <span class="hljs-string">'root'</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> LoggerService {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) { }
}
</code></pre>
<p>The logic of a service is distinct within its class. Angular interprets a class as an <em>injectable</em> service based off the <code>@Injectable</code> decorator. Injectable services must <em>register</em> with an injector.</p>
<p>The component instantiates a service while the injector provides that instance. Keep reading into the next section for more on injectors.</p>
<p>The <code>@Injectable</code> metadata field <code>providedIn: ‘root’</code> targets the root module of the current application (<code>app.module.ts</code>). It registers the service with the module’s injector so that it can <em>inject</em> that service into any of its children.</p>
<p>Injectors are the building blocks of Angular’s dependency injection system. Injectors are a good place to focus your attention before continuing with services.</p>
<h2 id="heading-injectors">Injectors</h2>
<p>An application, beginning with <code>app.module.ts</code>, contains a hierarchy of injectors. They exist alongside each module and component in the application tree.</p>
<p><img src="https://raw.githubusercontent.com/sosmaniac-FCC/designatedata/master/image5.png" alt="Application Hierarchy" width="599" height="433" loading="lazy"></p>
<p>The green circles indicate injectors. They provide service instances to instantiating components. Depending on which injector a service is registered with, it may or may not be available to a component.</p>
<p>Services registered at the root of the app (<code>app.module.ts</code>) are available to all components. An injector for a component may not have a certain service registered. If that is the case and the component requests its instantiation, the injector will defer to its parent. This trend continues until either reaching the root injector or the service is found.</p>
<p>Looking at the diagram, say that a service registers at point B’s injector. All components at point C and down will not be able to access the service registered at B’s injector. Injectors will never defer to their children for a service instance.</p>
<h3 id="heading-dependency-injection">Dependency Injection</h3>
<p>There are multiple ways to register a service with an application’s injectors.</p>
<p>The <code>providedIn: ‘root’</code> metadata field of <code>@Injectable</code> provides the most recommended approach. This metadata field released with Angular 6.</p>
<p>As mentioned before, <code>providedIn: ‘root’</code> registers a service with the root module injector. It is instantiable across the entire application as a result.</p>
<p>The novelty of <code>providedIn: ‘root’</code> is <em>tree-shaking</em>. If the service is unused despite its registration, it gets <em>shaken</em> from the application at run-time. That way it does not consume any resources.</p>
<p>The other two ways are more direct and traditional. Granted, they do not offer tree-shaking.</p>
<p>A service can register with any injector along the component tree. You insert the service as a provider in the <code>@Component</code> metadata field: <code>providers: []</code>. The service is available to the component and its children</p>
<p>In the third registration strategy, the <code>providers: []</code> metadata exists as its own field in the <code>@NgModule</code> decorator. The service is instantiable from the module to the underlying component tree.</p>
<p>Remember that unlike with <code>providedIn: ‘root’</code>, <code>@NgModule</code> registration does not offer tree-shaking. Both strategies are otherwise identical. Once a service registers with <code>@NgModule</code>, it consumes resources even if left unused by the application.</p>
<h2 id="heading-services-continued">Services Continued</h2>
<p>Writing an actual service comes next. To recap, services handle certain functions on behalf of an application’s components.</p>
<p>Services excel at handling common operations. They spare components the responsibility by doing so. It saves time not having to re-write common operations across multiple components. It is also more testable because the code is in one place. Changes only need to happen in one place without having to search elsewhere.</p>
<h2 id="heading-use-cases">Use Cases</h2>
<p>A couple examples goes a long way towards a complete understanding of services.</p>
<ul>
<li>console logs</li>
<li>API requests</li>
</ul>
<p>Both are common across most applications. Having services to handle these operations will reduce component complexity.</p>
<h3 id="heading-console-logs">Console Logs</h3>
<p>This example builds up from the base <code>@Injectable</code> skeleton. The skeleton is available through executing the CLI (<code>ng generate service [name-of-service]]</code>).</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// services/logger.service.ts</span>

<span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;

<span class="hljs-keyword">interface</span> LogMessage {
  message:<span class="hljs-built_in">string</span>;
  timestamp:<span class="hljs-built_in">Date</span>;
}

<span class="hljs-meta">@Injectable</span>({
  providedIn: <span class="hljs-string">'root'</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> LoggerService {
  callStack:LogMessage[] = [];

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) { }

  addLog(message:<span class="hljs-built_in">string</span>):<span class="hljs-built_in">void</span> {
      <span class="hljs-comment">// prepend new log to bottom of stack</span>
      <span class="hljs-built_in">this</span>.callStack = [{ message, timestamp: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>() }].concat(<span class="hljs-built_in">this</span>.callStack);
  }

  clear():<span class="hljs-built_in">void</span> {
      <span class="hljs-comment">// clear stack</span>
      <span class="hljs-built_in">this</span>.callStack = [];
  }

  printHead():<span class="hljs-built_in">void</span> {
      <span class="hljs-comment">// print bottom of stack</span>
      <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.callStack[<span class="hljs-number">0</span>] || <span class="hljs-literal">null</span>);
  }

  printLog():<span class="hljs-built_in">void</span> {
      <span class="hljs-comment">// print bottom to top of stack on screen</span>
      <span class="hljs-built_in">this</span>.callStack.reverse().forEach(<span class="hljs-function">(<span class="hljs-params">logMessage</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(logMessage));
  }

  getLog():LogMessage[] {
      <span class="hljs-comment">// return the entire log as an array</span>
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.callStack.reverse();
  }
}
</code></pre>
<p>LoggerService registers with the root module through the <code>@Injectable</code> metadata. Thus it can instantiate in the <code>app.component.html</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// app.component.ts</span>

<span class="hljs-keyword">import</span> { Component, OnInit } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { LoggerService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./services/logger.service'</span>;

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'app-root'</span>,
  templateUrl: <span class="hljs-string">'./app.component.html'</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppComponent <span class="hljs-keyword">implements</span> OnInit {
  logs:<span class="hljs-built_in">object</span>[] = [];

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> logger:LoggerService</span>) { }

  updateLog():<span class="hljs-built_in">void</span> {
      <span class="hljs-built_in">this</span>.logger.printHead();
      <span class="hljs-built_in">this</span>.logs = <span class="hljs-built_in">this</span>.logger.getLog();
  }

  logMessage(event:<span class="hljs-built_in">any</span>, message:<span class="hljs-built_in">string</span>):<span class="hljs-built_in">void</span> {
      event.preventDefault();

      <span class="hljs-built_in">this</span>.logger.addLog(<span class="hljs-string">`Message: <span class="hljs-subst">${message}</span>`</span>);
      <span class="hljs-built_in">this</span>.updateLog();
  }

  clearLog():<span class="hljs-built_in">void</span> {
      <span class="hljs-built_in">this</span>.logger.clear();
      <span class="hljs-built_in">this</span>.logs = [];
  }

  ngOnInit():<span class="hljs-built_in">void</span> {
      <span class="hljs-built_in">this</span>.logger.addLog(“View Initialized”);
      <span class="hljs-built_in">this</span>.updateLog();
  }
}
</code></pre>
<p>The template HTML provides further insight into the component’s use of LoggerService.</p>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- app.component.html --&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Log Example<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">form</span> (<span class="hljs-attr">submit</span>)=<span class="hljs-string">"logMessage($event, userInput.value)"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> #<span class="hljs-attr">userInput</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Type a message..."</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>SUBMIT<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Complete Log<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> (<span class="hljs-attr">click</span>)=<span class="hljs-string">"clearLog()"</span>&gt;</span>CLEAR<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span> *<span class="hljs-attr">ngFor</span>=<span class="hljs-string">"let log of logs; let i=index"</span>&gt;</span>{{ logs.length - i }} &gt; {{ log.message }} @ {{ log.timestamp }}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
</code></pre>
<p>This has the feel of a ToDo application. You can log messages and clear the log of messages. Imagine if all the logic from the service was shoved into AppComponent! It would have complicated the code. LoggerService keeps the log-related code encapsulated from the core AppComponent class.</p>
<h3 id="heading-fetch-requests">Fetch Requests</h3>
<p>Here is one more example worth playing around with. This example is possible thanks to <a target="_blank" href="https://jsonplaceholder.typicode.com/">typicode’s JSONPlaceholder<sup>1</sup></a>. The API is public and free to use.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { HttpClient } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/common/http'</span>;
<span class="hljs-keyword">import</span> { Observable } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs'</span>;

<span class="hljs-comment">// https://jsonplaceholder.typicode.com</span>
<span class="hljs-comment">// public API created by typicode @ https://github.com/typicode</span>

<span class="hljs-keyword">interface</span> Post {
  userId:<span class="hljs-built_in">number</span>;
  id:<span class="hljs-built_in">number</span>;
  title:<span class="hljs-built_in">string</span>;
  body:<span class="hljs-built_in">string</span>;
}

<span class="hljs-meta">@Injectable</span>({
  providedIn: <span class="hljs-string">'root'</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> PlaceholderService {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> http:HttpClient</span>) { }

  getPosts():Observable&lt;Post[]&gt; {
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.http.get(<span class="hljs-string">'https://jsonplaceholder.typicode.com/posts'</span>);
  }

  getPost(id:<span class="hljs-built_in">number</span>):Observable&lt;Post&gt; {
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.http.get(<span class="hljs-string">`https://jsonplaceholder.typicode.com/posts/<span class="hljs-subst">${id}</span>`</span>);
  }
}
</code></pre>
<p>This is more of a stand-alone piece than a fully fleshed out example. Fetch requests tend to work better as an injectable service. The alternative is an over-complicated component. The injected class subscribes to what the PlaceholderService pre-configures.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Services and dependency injection are very useful together. They allow developers to encapsulate common logic and inject across multiple different components. This alone is a massive convenience for any future maintenance.</p>
<p>Injectors work as intermediaries. They mediate between instantiating components and a reservoir of registered services. Injectors offer these instantiable services to their branch children.</p>
<p>See the next few links for more information on services and dependency injection.</p>
<h2 id="heading-resources-for-angular"><strong>Resources for Angular</strong></h2>
<ul>
<li><a target="_blank" href="https://angular.io/docs">Angular Documentation</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/angular-dependency-injection-in-detail-8b6822d6457c/">In introduction to Angular dependency injection</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/a-quick-intro-to-dependency-injection-what-it-is-and-when-to-use-it-7578c84fa88f/">What is dependency injection and when to use it</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/the-best-angular-examples/">Best Angular code examples</a></li>
<li><a target="_blank" href="https://github.com/angular/angular">Angular GitHub Repository</a></li>
<li><a target="_blank" href="https://angular.io/guide/dependency-injection-pattern">Dependency Injection</a></li>
<li><a target="_blank" href="https://angular.io/guide/architecture-services">Intro to Services and DI</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Node.js Development with modern JavaScript using FortJs ]]>
                </title>
                <description>
                    <![CDATA[ By Ujjwal Gupta Introduction Nodejs gives you the power to write server side code using JavaScript. In fact, it is very easy and fast to create a web server using Nodejs. There are several frameworks available on Node package manager which makes the ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/nodejs-development-with-modern-javascript-using-fortjs/</link>
                <guid isPermaLink="false">66d461728812486a37369d6c</guid>
                
                    <category>
                        <![CDATA[ dependency injection ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ REST ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 23 Oct 2019 02:37:44 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-20-36-31-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ujjwal Gupta</p>
<h2 id="heading-introduction">Introduction</h2>
<p>Nodejs gives you the power to write server side code using JavaScript. In fact, it is very easy and fast to create a web server using Nodejs. There are several frameworks available on Node package manager which makes the development even easier and faster.</p>
<p>But there are a few challenges in Nodejs development:</p>
<ul>
<li>Nodejs is all about callbacks, and with more and more callbacks you end up with a situation called callback hell.</li>
<li>Writing readable code.</li>
<li>Writing maintainable code.</li>
<li>You don't get much intellisense support which makes development slow.</li>
</ul>
<p>If you are quite experienced and have a good knowledge of Nodejs, you can use different techniques and try to minimize these challenges.</p>
<p>The best way to solve these problems is by using modern JavaScript ES6, ES7 or TypeScript, whatever you feel comfortable with. I recommend TypeScript, because it provides intillisense support for every word of code which makes your development faster.</p>
<p>So I created a framework called <a target="_blank" href="http://fortjs.info/">FortJs</a> which is very easy to learn and use. FortJs enables you to write server-side code using ES6 or TypeScript which is modular, secure, and pretty much just beautiful and readable.</p>
<h2 id="heading-features">Features</h2>
<p>Some of the important features of FortJs are:  </p>
<ul>
<li>Based on <a target="_blank" href="https://github.com/ujjwalguptaofficial/fort">Fort</a> architecture. </li>
<li>MVC Framework and follows OOPS approach so everything is class and object.</li>
<li>Provides components - Wall, Shield and Guard. Components help modularize the application.</li>
<li>Uses ES6 async/await or promise for executing asychronous code.</li>
<li>Everything is configurable - you can configure your session store, view engine, websocket etc.</li>
<li>Dependency Injection.</li>
<li>Everything can be unit tested, so you can use a <a target="_blank" href="https://guide.freecodecamp.org/agile/test-driven-development/">TDD</a> approach.</li>
</ul>
<h2 id="heading-lets-code">Let's Code</h2>
<p>In this article I am going to create a REST API using FortJs and ES6. But you can use the same code and steps to implement using TypeScript too.</p>
<h3 id="heading-project-setup">Project Setup</h3>
<p>FortJs provides a CLI - fort-creator. This helps you set up the project and develop faster. Let's use the CLI to develop.</p>
<p> Perform the below steps sequentially:</p>
<ul>
<li>Open your terminal or command prompt.</li>
<li>Install <strong>fort-creator</strong> globally - run the command "npm i fort-creator -g". Note: Make sure you have Nodejs installed in your system.</li>
<li>Create a new project - run the command "fort-creator new my-app". Here “my-app” is the name of the app, so you can choose any name. The CLI will prompt you to choose the language with two options: TypeScript and JavaScript. Choose your language by using the arrow keys and press enter - i have chosen JavaScript. It will take some time to create the project, so please wait until you see "new project my-app created".</li>
<li>Enter into the project directory - "cd my-app".<br>Start the development server with live reloading - run the command "fort-creator start".</li>
<li>Open the browser and type the URL - <a target="_blank" href="http://localhost:4000/">http://localhost:4000/</a>.  </li>
</ul>
<p>You should see something like this in the browser.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-20-36-31.png" alt="Image" width="600" height="400" loading="lazy">
<em>FortJs starter page</em></p>
<p>Let's understand how this page is rendered:</p>
<ul>
<li>Open the project folder in your favourite code editor. I am going to use VS Code. You will see many folders inside project root such as controllers, views, etc. Every folder is grouped by their use - for example, the controllers folder contains all controllers and the views folder contains all views.</li>
<li>Open the controllers folder -&gt; Inside the controllers, you will see a file name - default_controller. Let's open it and observe the code. The file contains a class DefaultController - this is a <a target="_blank" href="http://fortjs.info/tutorial/controller/">controller</a> class and it contains methods which return some http response.</li>
<li>Inside the class DefaultController, you will see a method 'index' - this is the one which is rendering current output to the browser. The method is known as <a target="_blank" href="http://fortjs.info/tutorial/worker/">worker</a> in FortJs because they do some kind of work and return the result as an http response. Let's observe the index method code:  </li>
</ul>
<pre><code><span class="hljs-keyword">const</span> data = {  
    <span class="hljs-attr">title</span>: title  
}  
<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> viewResult(<span class="hljs-string">'default/index.html'</span>, data);  
<span class="hljs-keyword">return</span> result;
</code></pre><p>It creates a data object and passes that object into the <strong>viewResult</strong> method. The <strong>viewResult</strong> method takes two parameters - the view location and view data. The work of <strong>viewResult</strong> is to render the view and return a response, which we are seeing in the browser.</p>
<ul>
<li>Let's find the view code and understand it. Open the views folder - &gt; open default folder - &gt; open index.html. This is our view code. It is simple HTML code along with some mustache syntax. The default view engine for Fortjs is mustache.</li>
</ul>
<p>I hope you have understood the project architecture. If you are having any difficulties or doubts, please feel free to ask in the comments section.</p>
<p>Now we will move to next part of this article where we will learn how to create a simple rest API.</p>
<h2 id="heading-rest">REST</h2>
<p>We are going to create a REST endpoint for entity user - which will perform CRUD operations for the user such as adding a user, deleting a user, getting a user, and updating a user.</p>
<p>According to REST:</p>
<ol>
<li>Adding user - should be done using the http method "<code>POST</code>"</li>
<li>Deleting user - should be done using the http method "<code>REMOVE</code>"</li>
<li>Getting user - should be done using the http method "<code>GET</code>"</li>
<li>Updating user - should be done using the http method "<code>PUT</code>"</li>
</ol>
<p>For creating an endpoint, we need to create a Controller similar to the default controller explained earlier.</p>
<p>Execute the command  "<code>fort-creator add</code>". It will ask you to "Choose the component to add ?" Choose Controller &amp; press <strong>enter</strong>. Enter the controller name "User" and press <strong>enter</strong>.</p>
<p>Now that we have created the user controller we need to inform FortJs by adding it to routes. The route is used to map our controller to a path.</p>
<p>Since our entity is user, "<code>/user</code>" will be a good route. Let's add it. Open routes.js inside the root directory of the project and add <code>UserController</code> to routes.</p>
<p>After adding UserController, routes.js will look like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { DefaultController } <span class="hljs-keyword">from</span> <span class="hljs-string">"./controllers/default_controller"</span>;
<span class="hljs-keyword">import</span> { UserController } <span class="hljs-keyword">from</span> <span class="hljs-string">"./controllers/user_controller"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> routes = [{
    <span class="hljs-attr">path</span>: <span class="hljs-string">"/*"</span>,
    <span class="hljs-attr">controller</span>: DefaultController
},
{
    <span class="hljs-attr">path</span>: <span class="hljs-string">"/user"</span>,
    <span class="hljs-attr">controller</span>: UserController
}]
</code></pre>
<p>So when an http request has the path "/user" then UserController will be called. </p>
<p>Let's open the url - <a target="_blank" href="http://localhost:4000/user">http://localhost:4000/user</a>.</p>
<p>Note: If you have stopped FortJs while adding the controller, please start it again by running the cmd - <code>fort-creator start</code></p>
<p>And you see a white page right?</p>
<p>This is because we are not returning anything from the index method and thus we get a blank response. Let's return a text "Hello World" from the index method. Add the below code inside the index method and save:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">return</span> textResult(<span class="hljs-string">'Hello World'</span>);
</code></pre>
<p>Refresh the url - <a target="_blank" href="http://localhost:4000/user">http://localhost:4000/user</a></p>
<p>And you see "Hello World" right?</p>
<p>Now, let's convert "UserController" to a REST API. But before writing code for the REST API, let's create a dummy service which will do CRUD operations for users.</p>
<h3 id="heading-service">Service</h3>
<p>Create a folder called “services” and then a file “user_service.js” inside the folder. Paste the below code inside the file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> store = {
    <span class="hljs-attr">users</span>: [{
        <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
        <span class="hljs-attr">name</span>: <span class="hljs-string">"ujjwal"</span>,
        <span class="hljs-attr">address</span>: <span class="hljs-string">"Bangalore India"</span>,
        <span class="hljs-attr">emailId</span>: <span class="hljs-string">"ujjwal@mg.com"</span>,
        <span class="hljs-attr">gender</span>: <span class="hljs-string">"male"</span>,
        <span class="hljs-attr">password</span>: <span class="hljs-string">"admin"</span>
    }]
}

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserService</span> </span>{
    getUsers() {
        <span class="hljs-keyword">return</span> store.users;
    }

    addUser(user) {
        <span class="hljs-keyword">const</span> lastUser = store.users[store.users.length - <span class="hljs-number">1</span>];
        user.id = lastUser == <span class="hljs-literal">null</span> ? <span class="hljs-number">1</span> : lastUser.id + <span class="hljs-number">1</span>;
        store.users.push(user);
        <span class="hljs-keyword">return</span> user;
    }

    updateUser(user) {
        <span class="hljs-keyword">const</span> existingUser = store.users.find(<span class="hljs-function"><span class="hljs-params">qry</span> =&gt;</span> qry.id === user.id);
        <span class="hljs-keyword">if</span> (existingUser != <span class="hljs-literal">null</span>) {
            existingUser.name = user.name;
            existingUser.address = user.address;
            existingUser.gender = user.gender;
            existingUser.emailId = user.emailId;
            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
        }
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }

    getUser(id) {
        <span class="hljs-keyword">return</span> store.users.find(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> user.id === id);
    }

    removeUser(id) {
        <span class="hljs-keyword">const</span> index = store.users.findIndex(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> user.id === id);
        store.users.splice(index, <span class="hljs-number">1</span>);
    }
}
</code></pre>
<p>The above code contains a variable store which contains a collection of users. The method inside the service does operations like add, update, delete, and get on that store.</p>
<p>We will use this service in REST API implementation.</p>
<h3 id="heading-get">GET</h3>
<p>For the route "/user" with the http method "GET", the API should return a list of all users. </p>
<p>In order to implement this, let's rename the "index" method inside user_controller.js to "getUsers" making it semantically correct. Then paste the below code inside the method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> service = <span class="hljs-keyword">new</span> UserService();
<span class="hljs-keyword">return</span> jsonResult(service.getUsers());
</code></pre>
<p>Now user_controller.js looks like this:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> { Controller, DefaultWorker, Worker, textResult, jsonResult } <span class="hljs-keyword">from</span> <span class="hljs-string">"fortjs"</span>;
<span class="hljs-keyword">import</span> { UserService } <span class="hljs-keyword">from</span> <span class="hljs-string">"../services/user_service"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span> </span>{

    @DefaultWorker()
    <span class="hljs-keyword">async</span> getUsers() {
        <span class="hljs-keyword">const</span> service = <span class="hljs-keyword">new</span> UserService();
        <span class="hljs-keyword">return</span> jsonResult(service.getUsers());
    }
}
</code></pre>
<p>Here, we are using the decorator DefaultWorker. The DefaultWorker does two things: it adds the route "/" &amp; the http method "GET". It's a shortcut for this scenario. In the next part, we will use other decorators to customize the route.</p>
<p>Let's test this by calling the url <a target="_blank" href="http://localhost:4000/user">http://localhost:4000/user</a>. You can open this in the browser or use any http client tools like postman or curl. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-21-53-59.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Ok, so we have successfully created an end point :) .</p>
<p>Let's look again at our code and see if we can make it better: </p>
<ol>
<li>The service "UserService" is tightly coupled with Controller "UserController" which becomes a problem for unit testing "UserController". So we will use <a target="_blank" href="http://fortjs.info/tutorial/dependency-injection/">dependency injection</a> by FortJs to inject UserService.</li>
<li>We are creating an instance of "UserService" every time the method getUsers is called. But what we need from "UserService" is a single object and then call the "UserService" method from the object. </li>
</ol>
<p>So if we can somehow store an object of "UserService" then we can make our code faster (because calling new does some work under the hood). For this we will use the singleton feature of FortJs.</p>
<p>Let's change the user_controller.js code by the below code: </p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> { Controller, DefaultWorker, Worker, textResult, jsonResult, Singleton } <span class="hljs-keyword">from</span> <span class="hljs-string">"fortjs"</span>;
<span class="hljs-keyword">import</span> { UserService } <span class="hljs-keyword">from</span> <span class="hljs-string">"../services/user_service"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span> </span>{

    @DefaultWorker()
    <span class="hljs-keyword">async</span> getUsers(@Singleton(UserService) service) {
        <span class="hljs-keyword">return</span> jsonResult(service.getUsers());
    }
}
</code></pre>
<p>As you can see, the only change is that we are using the "Singleton" decorator in the method getUsers. This will create a singleton and inject that singleton when getUsers is called. This singleton will be available throughout the application.</p>
<p>Since service is now a parameter, we can manually pass the parameter while calling. This makes getUsers unit testable.</p>
<p>For doing unit testing or E2E testing, please read this test doc - <a target="_blank" href="http://fortjs.info/tutorial/test/">http://fortjs.info/tutorial/test/</a></p>
<h3 id="heading-post">POST</h3>
<p>Let's add a method "addUser" which will extract data from the request body and call service to add a user.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> addUser(@Singleton(UserService) service) {
        <span class="hljs-keyword">const</span> user = {
            <span class="hljs-attr">name</span>: <span class="hljs-built_in">this</span>.body.name,
            <span class="hljs-attr">gender</span>: <span class="hljs-built_in">this</span>.body.gender,
            <span class="hljs-attr">address</span>: <span class="hljs-built_in">this</span>.body.address,
            <span class="hljs-attr">emailId</span>: <span class="hljs-built_in">this</span>.body.emailId,
            <span class="hljs-attr">password</span>: <span class="hljs-built_in">this</span>.body.password
        };
        <span class="hljs-keyword">const</span> newUser = service.addUser(user);
        <span class="hljs-keyword">return</span> jsonResult(newUser, HTTP_STATUS_CODE.Created);
}
</code></pre>
<blockquote>
<p>In the above code we are creating the Singleton of the UserService again. So the question is will it create another object?</p>
</blockquote>
<p>No it will be same object that was in getUser. FortJs supplies the object as a parameter when it calls the method.</p>
<p>The methods created are by default not visible for an http request. So in order to make this method visible for the http request, we need to mark this as a worker. </p>
<p>A method is marked as a worker by adding the decorator "Worker". The Worker decorator takes a list of http methods and makes that method available for only those http methods. So let's add the decorator:</p>
<pre><code class="lang-javascript">@Worker([HTTP_METHOD.Post])
<span class="hljs-keyword">async</span> addUser(@Singleton(UserService) service) {
    <span class="hljs-keyword">const</span> user = {
        <span class="hljs-attr">name</span>: <span class="hljs-built_in">this</span>.body.name,
        <span class="hljs-attr">gender</span>: <span class="hljs-built_in">this</span>.body.gender,
        <span class="hljs-attr">address</span>: <span class="hljs-built_in">this</span>.body.address,
        <span class="hljs-attr">emailId</span>: <span class="hljs-built_in">this</span>.body.emailId,
        <span class="hljs-attr">password</span>: <span class="hljs-built_in">this</span>.body.password
    };
    <span class="hljs-keyword">const</span> newUser = service.addUser(user);
    <span class="hljs-keyword">return</span> jsonResult(newUser, HTTP_STATUS_CODE.Created);
}
</code></pre>
<p>Now the route of this method is the same as the name of the method that is "addUser". You can check this by sending a post request to <a target="_blank" href="http://localhost:4000/user/addUser">http://localhost:4000/user/addUser</a> with user data in the body.</p>
<p>But we want the route to be "/", so that it will be a rest API. The route of the worker is configured by using the decorator "Route". Let's change the route now.</p>
<pre><code>@Worker([HTTP_METHOD.Post])
@Route(<span class="hljs-string">"/"</span>)
<span class="hljs-keyword">async</span> addUser(@Singleton(UserService) service) {
    <span class="hljs-keyword">const</span> user = {
        <span class="hljs-attr">name</span>: <span class="hljs-built_in">this</span>.body.name,
        <span class="hljs-attr">gender</span>: <span class="hljs-built_in">this</span>.body.gender,
        <span class="hljs-attr">address</span>: <span class="hljs-built_in">this</span>.body.address,
        <span class="hljs-attr">emailId</span>: <span class="hljs-built_in">this</span>.body.emailId,
        <span class="hljs-attr">password</span>: <span class="hljs-built_in">this</span>.body.password
    };
    <span class="hljs-keyword">const</span> newUser = service.addUser(user);
    <span class="hljs-keyword">return</span> jsonResult(newUser, HTTP_STATUS_CODE.Created);
}
</code></pre><p>Now our end point is configured for a post request. Let's test this by sending a post request to <a target="_blank" href="http://localhost:4000/user/">http://localhost:4000/user/</a> with user data in the body.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-22-43-19.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>It returns the user created with id which is our logic. So we have created the end point for the post request, but one important thing to do is to validate the data. Validation is an essential part of any app and is very important for a backend application.</p>
<p>So far, our code is clean and readable. But if we add validation code it will become a little dirty. </p>
<p>Worry not, FortJs provides the component <a target="_blank" href="http://fortjs.info/tutorial/guard/">Guard</a> for this kind of work. A/c to the FortJs docs:</p>
<blockquote>
<p>Guard is security layer on top of Worker. It controls whether a request should be allowed to call the Worker.</p>
</blockquote>
<p>So we are going to use guard for validation of the data. Let's create the guard using fort-creator. Execute the command  <code>fort-creator add</code> and choose Guard. Enter the file name "UserValidator". There will be a file "user_validator_guard.js" created inside the guards folder. Open that file.</p>
<p>A guard has access to the body, so you can validate the data inside that. Returning null inside the method <code>check</code> means that we're allowing to call the worker. Returning anything else means block the call.</p>
<p>Let's make it clearer by writing code for the validation. Paste the below code inside the file "user_validator_guard.js":</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> { Guard, textResult, HTTP_STATUS_CODE } <span class="hljs-keyword">from</span> <span class="hljs-string">"fortjs"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserValidatorGuard</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Guard</span> </span>{

    <span class="hljs-keyword">async</span> check() {
        <span class="hljs-keyword">const</span> user = {
            <span class="hljs-attr">name</span>: <span class="hljs-built_in">this</span>.body.name,
            <span class="hljs-attr">gender</span>: <span class="hljs-built_in">this</span>.body.gender,
            <span class="hljs-attr">address</span>: <span class="hljs-built_in">this</span>.body.address,
            <span class="hljs-attr">emailId</span>: <span class="hljs-built_in">this</span>.body.emailId,
            <span class="hljs-attr">password</span>: <span class="hljs-built_in">this</span>.body.password
        };
        <span class="hljs-keyword">const</span> errMsg = <span class="hljs-built_in">this</span>.validate(user);
        <span class="hljs-keyword">if</span> (errMsg == <span class="hljs-literal">null</span>) {
            <span class="hljs-comment">// pass user to worker method, so that they dont need to parse again  </span>
            <span class="hljs-built_in">this</span>.data.user = user;
            <span class="hljs-comment">// returning null means - guard allows request to pass  </span>
            <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">return</span> textResult(errMsg, HTTP_STATUS_CODE.BadRequest);
        }
    }

    validate(user) {
        <span class="hljs-keyword">let</span> errMessage;
        <span class="hljs-keyword">if</span> (user.name == <span class="hljs-literal">null</span> || user.name.length &lt; <span class="hljs-number">5</span>) {
            errMessage = <span class="hljs-string">"name should be minimum 5 characters"</span>
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (user.password == <span class="hljs-literal">null</span> || user.password.length &lt; <span class="hljs-number">5</span>) {
            errMessage = <span class="hljs-string">"password should be minimum 5 characters"</span>;
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (user.gender == <span class="hljs-literal">null</span> || [<span class="hljs-string">"male"</span>, <span class="hljs-string">"female"</span>].indexOf(user.gender) &lt; <span class="hljs-number">0</span>) {
            errMessage = <span class="hljs-string">"gender should be either male or female"</span>;
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (user.emailId == <span class="hljs-literal">null</span> || !<span class="hljs-built_in">this</span>.isValidEmail(user.emailId)) {
            errMessage = <span class="hljs-string">"email not valid"</span>;
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (user.address == <span class="hljs-literal">null</span> || user.address.length &lt; <span class="hljs-number">10</span>) {
            errMessage = <span class="hljs-string">"address length should be greater than 10"</span>;
        }
        <span class="hljs-keyword">return</span> errMessage;
    }

    isValidEmail(email) {
        <span class="hljs-keyword">var</span> re = <span class="hljs-regexp">/^(([^&lt;&gt;()\[\]\\.,;:\s@"]+(\.[^&lt;&gt;()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/</span>;
        <span class="hljs-keyword">return</span> re.test(<span class="hljs-built_in">String</span>(email).toLowerCase());
    }


}
</code></pre>
<p>In the above code:</p>
<ul>
<li>We have created a method validate which takes the parameter user. It validates the user &amp; returns the error message if there is a validation error, otherwise null.</li>
<li>We are validating data inside the check method, which is part of guard lifecycle. We are validating the user inside it by calling the method validate.<br>If the user is valid, then we are passing the user value by using the "data" property and returning null. Returning null means guard has allowed this request and the worker should be called.</li>
<li>If a user is not valid, we are returning an error message as a text response with the HTTP code "Bad Request". In this case, execution will stop here and the worker won't be called.</li>
</ul>
<p>In order to activate this guard for the method addUser, we need to add this on top of addUser. The guard is added by using the decorator "Guards". So let's add the guard:</p>
<pre><code class="lang-javascript">@Worker([HTTP_METHOD.Post])
@Route(<span class="hljs-string">"/"</span>)
@Guards([UserValidatorGuard])
<span class="hljs-keyword">async</span> addUser(@Singleton(UserService) service) {
    <span class="hljs-keyword">const</span> newUser = service.addUser(<span class="hljs-built_in">this</span>.data.user);
    <span class="hljs-keyword">return</span> jsonResult(newUser, HTTP_STATUS_CODE.Created);
}
</code></pre>
<p>In the above code:</p>
<ul>
<li>I have added the guard, “UserValidatorGuard” using the decorator Guards.</li>
<li>With the guard in the process, we don't need to parse the data from the body anymore inside the worker. Rather, we are reading it from this.data which we are passing from "UserValidatorGuard".</li>
<li>The method “addUser” will only be called when Guard allows, which means all data is valid.</li>
</ul>
<p>One thing to note is that the method "addUser" looks very light after using a component, and it's doing validation too. You can add multiple guards to a worker which gives you the ability to modularize your code into multiple guards and use that guard at multiple places.</p>
<blockquote>
<p>Isn't this cool :D?</p>
</blockquote>
<p>Let's try adding a user with some invalid data:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-23-21-37.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you can see in the screenshot, I have tried sending a request without a password. The result is - "password should be minimum 5 characters". So it means that guard is activated and working perfectly.</p>
<h3 id="heading-put">PUT</h3>
<p>Let’s add another method - “updateUser” with route “/” , guard “UserValidatorGuard” (for validation of user) and most important - worker with http method “PUT”.</p>
<pre><code class="lang-javascript">@Worker([HTTP_METHOD.Put])
@Guards([UserValidatorGuard])
@Route(<span class="hljs-string">"/"</span>)
<span class="hljs-keyword">async</span> updateUser(@Singleton(UserService) service) {
    <span class="hljs-keyword">const</span> user = <span class="hljs-built_in">this</span>.data.user;
    <span class="hljs-keyword">const</span> userUpdated = service.updateUser(user);
    <span class="hljs-keyword">if</span> (userUpdated === <span class="hljs-literal">true</span>) {
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"user updated"</span>);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"invalid user"</span>);
    }
}
</code></pre>
<p>The updated code is similar to the addUser code except functionality wise it is updating the data. Here, we have reutilized UserValidatorGuard to validate data.</p>
<h3 id="heading-delete">DELETE</h3>
<p>In order to delete data, user needs to pass the id of the user. This can be passed by:</p>
<ul>
<li>Sending data in body just like we did for add &amp; update - {id:1}</li>
<li>Sending data in query string - ?id=1</li>
<li>Sending data in route - for this, we need to customize our route - "/user/1"</li>
</ul>
<p>We have already implemented getting data from body. So let's see other two ways:</p>
<p><strong>Sending Data in Query String</strong></p>
<p>Let's create a method "removeByQueryString" and paste the below code:</p>
<pre><code class="lang-javascript">@Worker([HTTP_METHOD.Delete])
@Route(<span class="hljs-string">"/"</span>)
<span class="hljs-keyword">async</span> removeByQueryString(@Singleton(UserService) service) {
    <span class="hljs-comment">// taking id from query string</span>
    <span class="hljs-keyword">const</span> userId = <span class="hljs-built_in">Number</span>(<span class="hljs-built_in">this</span>.query.id);
    <span class="hljs-keyword">const</span> user = service.getUser(userId);
    <span class="hljs-keyword">if</span> (user != <span class="hljs-literal">null</span>) {
        service.removeUser(userId);
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"user deleted"</span>);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"invalid user"</span>, <span class="hljs-number">404</span>);
    }
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-23-40-34.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Sending Data in Route</strong></p>
<p>You can parameterise the route by using "{var}" in a route. Let's see how.</p>
<p>Let's create another method "removeByRoute" and paste the below code:</p>
<pre><code class="lang-javascript">@Worker([HTTP_METHOD.Delete])
@Route(<span class="hljs-string">"/{id}"</span>)
<span class="hljs-keyword">async</span> removeByRoute(@Singleton(UserService) service) {

    <span class="hljs-comment">// taking id from route</span>
    <span class="hljs-keyword">const</span> userId = <span class="hljs-built_in">Number</span>(<span class="hljs-built_in">this</span>.param.id);

    <span class="hljs-keyword">const</span> user = service.getUser(userId);
    <span class="hljs-keyword">if</span> (user != <span class="hljs-literal">null</span>) {
        service.removeUser(userId);
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"user deleted"</span>);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> textResult(<span class="hljs-string">"invalid user"</span>);
    }
}
</code></pre>
<p>The above code is exactly the same as removeByQueryString except that it is extracting the id from the route and using parameter in route i.e., "/{id}" where id is parameter.</p>
<p>Let's test this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/Screenshot-from-2019-10-20-23-46-42.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>So we have finally created a REST API for all the funtionalities except GETting a particular user by id. I will leave that to you for practice.</p>
<h2 id="heading-points-of-interest">POINTS OF INTEREST</h2>
<p>Q: How do we add authentication to "UserController", so that any unauthenticated request can't call the "/user" end point.</p>
<p>A: There are multiple approaches for this: </p>
<ul>
<li>We can check in every worker for authentication. (BAD - so much extra work and code repetition)</li>
<li>Create a Guard component and assign to every worker . (GOOD) </li>
<li>Create a <a target="_blank" href="http://fortjs.info/tutorial/shield/">Shield</a> component and assign to controller. Shield is a security layer similar to guard but works on top of controller, so if shield rejects then controller is not initiated. (BEST)</li>
</ul>
<p>Take a look at the FortJs authentication docs - <a target="_blank" href="http://fortjs.info/tutorial/authentication/">http://fortjs.info/tutorial/authentication/</a></p>
<h2 id="heading-references">REFERENCES</h2>
<ul>
<li><a target="_blank" href="http://fortjs.info/">http://fortjs.info/</a></li>
<li><a target="_blank" href="https://medium.com/fortjs">https://medium.com/fortjs</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An introduction to Angular dependency injection ]]>
                </title>
                <description>
                    <![CDATA[ By Neeraj Dana In this article, we will see how the dependency injection of Angular works internally. Suppose we have a component named appcomponent which has a basic and simple structure as follows: import { Component, OnInit } from "@angular/core";... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/angular-dependency-injection-in-detail-8b6822d6457c/</link>
                <guid isPermaLink="false">66c344a852e2abc555bfcc07</guid>
                
                    <category>
                        <![CDATA[ Angular ]]>
                    </category>
                
                    <category>
                        <![CDATA[ dependency injection ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 25 Jan 2019 21:14:06 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*xQW9Spiz8U0tNEuX_m2blw.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Neeraj Dana</p>
<p>In this article, we will see how the dependency injection of Angular works internally. Suppose we have a component named appcomponent which has a basic and simple structure as follows:</p>
<pre><code><span class="hljs-keyword">import</span> { Component, OnInit } <span class="hljs-keyword">from</span> <span class="hljs-string">"@angular/core"</span>;@Component({  <span class="hljs-attr">selector</span>: <span class="hljs-string">"my-root"</span>,  <span class="hljs-attr">templateUrl</span>: <span class="hljs-string">"app.component.html"</span>,  <span class="hljs-attr">styleUrls</span>: [<span class="hljs-string">"app.component.css"</span>]})<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppComponent</span> <span class="hljs-title">implements</span> <span class="hljs-title">OnInit</span> </span>{  ngOnInit(): <span class="hljs-keyword">void</span> {      }}
</code></pre><p>And we have a service class named GreetingService with a function in it <code>sayHello</code> which has a name as a parameter and returns the name with “Hello” in front of it.</p>
<pre><code><span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GreetingService</span></span>{  sayHello(name){    <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello <span class="hljs-subst">${name}</span>`</span> ;  }}
</code></pre><p>There are two ways to use the service class in the component: first, we can manually create an instance of the service in the component (this is the wrong way and is never recommended).</p>
<p>And the other way is to let Angular create the instance of our service and pass that instance to our component internally. This is the common and recommended way to do it.</p>
<h4 id="heading-injecting-our-service-in-the-angular-dependency-injection-system">Injecting our service in the Angular dependency injection system</h4>
<pre><code>Import {Component} <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;Import {GreetingService} <span class="hljs-keyword">from</span> <span class="hljs-string">'. /greetingService'</span>;
</code></pre><pre><code>@Component({  <span class="hljs-attr">selector</span>: <span class="hljs-string">'my-app'</span>,  <span class="hljs-attr">templateUrl</span>: <span class="hljs-string">'./app.component.html'</span>,  <span class="hljs-attr">styleUrls</span>: [ <span class="hljs-string">'./app.component.css'</span> ]})<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppComponent</span>  </span>{
</code></pre><pre><code><span class="hljs-keyword">constructor</span>(private greetingService : GreetingService){   <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.greetingService.sayHello());  }}
</code></pre><p>Now if you run this project, you will get the error “No provider for GreetingService!”</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/PA66RsT3fdnjttQROpVulvpDU6QGWfYoCxyl" alt="Image" width="800" height="273" loading="lazy"></p>
<p>So, basically Angular is complaining that it did not find any provider for creating an instance of the greeting service or it does not know how to create an instance. In order to let the framework know how the instance should be created, we have to pass a provider object to the providers property in the component decorator shown below:</p>
<pre><code><span class="hljs-keyword">import</span> { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;<span class="hljs-keyword">import</span> {GreetingService} <span class="hljs-keyword">from</span> <span class="hljs-string">'./greetingService'</span>;
</code></pre><pre><code>@Component({  <span class="hljs-attr">selector</span>: <span class="hljs-string">'my-app'</span>,  <span class="hljs-attr">templateUrl</span>: <span class="hljs-string">'./app.component.html'</span>,  <span class="hljs-attr">styleUrls</span>: [ <span class="hljs-string">'./app.component.css'</span> ],  <span class="hljs-attr">providers</span>:[{      }]})<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppComponent</span>  </span>{
</code></pre><pre><code><span class="hljs-keyword">constructor</span>(private greetingService : GreetingService){   <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.greetingService.sayHello());  }  }
</code></pre><p>In this provider object, we have many properties so let us understand them one by one.</p>
<h4 id="heading-custom-factory">Custom Factory</h4>
<p>use factory: this will tell the framework which factory will be used while creating the object of the service. In our case, we don’t have any factory so let’s create one.</p>
<p>The factory will be a function which will be responsible for creating and returning the object of the service.</p>
<pre><code><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetingFactory</span>(<span class="hljs-params"></span>)</span>{   <span class="hljs-keyword">return</span>  <span class="hljs-keyword">new</span> GreetingService()};
</code></pre><pre><code>Or more short way
</code></pre><pre><code><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> greetingFactory= <span class="hljs-function">() =&gt;</span>  <span class="hljs-keyword">new</span> GreetingService ();
</code></pre><h4 id="heading-custom-injection-token">Custom Injection Token</h4>
<p>The next thing is to create a property whose value will be an Injection Token instance. Using this property, the framework will uniquely identify our service and will inject the right instance of the service.</p>
<pre><code><span class="hljs-keyword">var</span> greetingTokken = <span class="hljs-keyword">new</span> InjectionToken&lt;GreetingService&gt;(<span class="hljs-string">"GREET_TOKEN"</span>);
</code></pre><p>So in the above snippet, we are creating an instance of the InjectionToken class and it is generic. In our case, the GreetingService instance will be injected when someone asks for the injection with name greetingToken.</p>
<p>So far now our code will look like this:</p>
<pre><code><span class="hljs-keyword">import</span> { Component ,InjectionToken} <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;<span class="hljs-keyword">import</span> {GreetingService} <span class="hljs-keyword">from</span> <span class="hljs-string">'./greetingService'</span>;
</code></pre><pre><code><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> greetingTokken = <span class="hljs-keyword">new</span> InjectionToken&lt;GreetingService&gt;(<span class="hljs-string">"GREET_TOKEN"</span>);<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> greetingFactory=<span class="hljs-function">()=&gt;</span>  <span class="hljs-keyword">new</span> GreetingService();@Component({  <span class="hljs-attr">selector</span>: <span class="hljs-string">'my-app'</span>,  <span class="hljs-attr">templateUrl</span>: <span class="hljs-string">'./app.component.html'</span>,  <span class="hljs-attr">styleUrls</span>: [ <span class="hljs-string">'./app.component.css'</span> ],  <span class="hljs-attr">providers</span>:[{    <span class="hljs-attr">provide</span>  : greetingTokken,    <span class="hljs-attr">useFactory</span> : greetingFactory,     }]})<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppComponent</span>  </span>{
</code></pre><pre><code><span class="hljs-keyword">constructor</span>(private greetingService : GreetingService){   <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.greetingService.sayHello());  }  name = <span class="hljs-string">'Angular'</span>;}
</code></pre><p>But then also we will have the same error:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/yOKshbzOHxjiPigdOXBK8p-IUkH7wOc8wnf8" alt="Image" width="800" height="418" loading="lazy"></p>
<p>This is because in the constructor, where we are asking for the instance of our service, we have to tell it the unique string of our injection token that is <code>greetingToken</code>.</p>
<p>So let’s update our code:</p>
<pre><code><span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppComponent</span>  </span>{
</code></pre><pre><code><span class="hljs-keyword">constructor</span>(@Inject(greetingTokken) private greetingService : GreetingService){   <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.greetingService.sayHello(<span class="hljs-string">'Neeraj'</span>));  }  name = <span class="hljs-string">'Angular'</span>;}
</code></pre><p>and now we will have the result that allows us to successfully pass a service from Angular dependency injection.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/Z0y7nt8qPli6OdjGSse2dEhxJV11Mk-yQ4kz" alt="Image" width="800" height="452" loading="lazy"></p>
<p>Now let us assume you have some nested dependencies like this:</p>
<pre><code><span class="hljs-keyword">import</span>{DomSanitizer} <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/platform-browser'</span>;
</code></pre><pre><code><span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GreetingService</span></span>{  <span class="hljs-keyword">constructor</span> (private domSanitizer:DomSanitizer){      }  sayHello(name){    <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello <span class="hljs-subst">${name}</span>`</span>  }}
</code></pre><p>So, in this case, we have to pass one more property to the provider’s object (that is deps) which is the array of all the dependencies:</p>
<pre><code>@Component({  <span class="hljs-attr">selector</span>: <span class="hljs-string">'my-app'</span>,  <span class="hljs-attr">templateUrl</span>: <span class="hljs-string">'./app.component.html'</span>,  <span class="hljs-attr">styleUrls</span>: [ <span class="hljs-string">'./app.component.css'</span> ],  <span class="hljs-attr">providers</span>:[{    <span class="hljs-attr">provide</span>  : greetingTokken,    <span class="hljs-attr">useFactory</span> : greetingFactory,    <span class="hljs-attr">deps</span>:[DomSanitizer]     }]})<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppComponent</span>  </span>{
</code></pre><pre><code><span class="hljs-keyword">constructor</span>(@Inject(greetingTokken) private greetingService : GreetingService  ){   <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.greetingService.sayHello(<span class="hljs-string">'Neeraj'</span>));  }  name = <span class="hljs-string">'Angular'</span>;}
</code></pre><blockquote>
<p><strong><em>Up until now, whatever we have done has only been for learning purposes. It is not recommended to create manual providers until there is a need.</em></strong></p>
</blockquote>
<p>So this is all the hard work done by Angular behind the scenes for us. We don’t have to do all this for registering our service. We can actually reduce the code, and instead of passing the factory and token manually, we can ask the framework to do this for us in that case.</p>
<p>The provide property, which is the injection token, will be the name of the service and Angular will internally create an injection token and factory for us.</p>
<p>We have to pass one more property (use-class) which tells the framework which class we need to use:</p>
<pre><code><span class="hljs-keyword">import</span> { Component ,InjectionToken,Inject} <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
</code></pre><pre><code><span class="hljs-keyword">import</span> {GreetingService} <span class="hljs-keyword">from</span> <span class="hljs-string">'./greetingService'</span>;
</code></pre><pre><code>@Component({  <span class="hljs-attr">selector</span>: <span class="hljs-string">'my-app'</span>,  <span class="hljs-attr">templateUrl</span>: <span class="hljs-string">'./app.component.html'</span>,  <span class="hljs-attr">styleUrls</span>: [ <span class="hljs-string">'./app.component.css'</span> ],  <span class="hljs-attr">providers</span>:[{    <span class="hljs-attr">provide</span>  : GreetingService,    <span class="hljs-attr">useClass</span> :GreetingService     }]})<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppComponent</span>  </span>{
</code></pre><pre><code><span class="hljs-keyword">constructor</span>( private greetingService : GreetingService  ){   <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.greetingService.sayHello(<span class="hljs-string">'Neeraj'</span>));  }  name = <span class="hljs-string">'Angular'</span>;}
</code></pre><p>So now our code looks much cleaner and we can further reduce it by just passing the name of the service. Then Angular under the hood will create the provide object, the factory, and the injection token for us and make the instance available to us when needed.</p>
<pre><code><span class="hljs-keyword">import</span> { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
</code></pre><pre><code><span class="hljs-keyword">import</span> {GreetingService} <span class="hljs-keyword">from</span> <span class="hljs-string">'./greetingService'</span>;
</code></pre><pre><code>@Component({  <span class="hljs-attr">selector</span>: <span class="hljs-string">'my-app'</span>,  <span class="hljs-attr">templateUrl</span>: <span class="hljs-string">'./app.component.html'</span>,  <span class="hljs-attr">styleUrls</span>: [ <span class="hljs-string">'./app.component.css'</span> ],  <span class="hljs-attr">providers</span>:[GreetingService]})<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppComponent</span>  </span>{
</code></pre><pre><code><span class="hljs-keyword">constructor</span>( private greetingService : GreetingService  ){   <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.greetingService.sayHello(<span class="hljs-string">'Neeraj'</span>));  }  name = <span class="hljs-string">'Angular'</span>;}
</code></pre><p>So in the end, our code looks very familiar. Now in the future, whenever you create a service, you know exactly what steps are involved to get that instance available.</p>
<p>If you like this article follow me to get more of this kind of stuff.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/GHJHXu-n2p6nfjIZmNgTMyNt-MBPTvPRLTkt" alt="Image" width="800" height="151" loading="lazy"></p>
<p>Visit <a target="_blank" href="https://www.smartcodehub.com/">Smartcodehub</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A hands-on session with Google Guice ]]>
                </title>
                <description>
                    <![CDATA[ By Sankalp Bhatia A few months ago, I wrote an article explaining dependency injection. I had mentioned of a follow-up article with a hands-on session of Google Guice. While I am disappointed in being so late in writing this, part of me is happy that... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-hands-on-session-with-google-guice-5f25ce588774/</link>
                <guid isPermaLink="false">66c342bf93db2451bd4413e7</guid>
                
                    <category>
                        <![CDATA[ dependency injection ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Google ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 30 Oct 2018 16:50:05 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*TUa3fApD5vZpVB7-d7mTaw.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Sankalp Bhatia</p>
<p>A few months ago, I wrote <a target="_blank" href="https://medium.freecodecamp.org/demystifying-dependency-injection-49d4b6fe6536">an article</a> explaining dependency injection. I had mentioned of a follow-up article with a hands-on session of Google Guice. While I am disappointed in being so late in writing this, part of me is happy that I was able to write a second article.</p>
<p>This article assumes that you are familiar with what dependency injection is. I would recommend you to glance through <a target="_blank" href="https://medium.freecodecamp.org/demystifying-dependency-injection-49d4b6fe6536">my previous article</a> as we will be building upon the examples we used there. If you are hearing the term for the first time, it will be worth it. If you are familiar with it, reading it won’t take much time :)</p>
<p>If you haven’t worked much with Guice, please check it out on GitHub <a target="_blank" href="https://github.com/google/guice">here</a>.</p>
<p>We will need to set up a few things before we start</p>
<ol>
<li><strong>JDK</strong>: We will be using Java for this task. So you will need to have a working JDK to be able to run Java code in your computer. To check if it’s already installed, run ‘java -version’ on the command line. If the version is 1.6 or greater, we are good. Just a note: I don’t think it would make much sense to attempt this if you don’t have experience with Java<em>.</em></li>
<li><strong>Maven</strong>: We will be using maven as a build tool. To install maven, follow the instructions here <a target="_blank" href="https://maven.apache.org/install.html">https://maven.apache.org/install.html</a> (Quite easy). To check if you already have maven, run ‘mvn -v’ on the command line.</li>
<li><strong>git</strong> (optional): <a target="_blank" href="https://www.linode.com/docs/development/version-control/how-to-install-git-on-linux-mac-and-windows/">https://www.linode.com/docs/development/version-control/how-to-install-git-on-linux-mac-and-windows/</a></li>
<li><strong>clone the hands on repository (FreshGuice)</strong>: Run commands mentioned below</li>
</ol>
<pre><code>cd folder/to/clone-into/ git clone https:<span class="hljs-comment">//github.com/sankalpbhatia/FreshGuice.git</span>
</code></pre><h3 id="heading-bindings-and-binding-annotations">Bindings and Binding Annotations</h3>
<p>We are ready now. Let me start by introducing two crucial terms in the Guice framework: <strong>Bindings and Binding Annotations.</strong></p>
<p><strong>Bindings:</strong> being the core concept of Guice, in literal terms, means an agreement or promise involving an obligation that cannot be broken. Now let’s map it in the context of Dependency Injection. When we make Guice <em>bind</em> an instance with a class, we make an agreement with Guice that “When I ask for an instance of X.java, give me this instance”. And this agreement can’t be broken.</p>
<p><strong>Binding Annotations:</strong> Occasionally you’ll want multiple bindings for the same type. The annotation and (class) type together uniquely identify a binding. For example, in some cases, you might need two separate instances of the same class/ implementation of the same interface. To identify those, we use binding annotations. We will see some examples when we explain bindings.</p>
<h4 id="heading-how-to-create-bindings"><strong>How to create bindings</strong></h4>
<p>The user guide section of Guice explains it perfectly. So I will just be copying it here:</p>
<blockquote>
<p>To create bindings, extend <code>AbstractModule</code> and override its <code>configure</code> method. In the method body, call <code>bind()</code> to specify each binding. These methods are type checked so the compiler can report errors if you use the wrong types. Once you've created your modules, pass them as arguments to <code>Guice.createInjector()</code> to build an injector.</p>
</blockquote>
<p>There are a number of types of bindings: Linked, Instance, @Provides annotation, Provider bindings, Constructor bindings, and Un-targeted bindings.</p>
<p>For this article, I will only be covering Linked Bindings, Instance Bindings, @Provides annotation, and a special annotation @Inject. I very rarely use any other means to bind, but more information can be found at <a target="_blank" href="https://github.com/google/guice/wiki/Bindings">https://github.com/google/guice/wiki/Bindings</a>.</p>
<ol>
<li><strong>Linked Binding:</strong> a Linked binding maps a type/interface to its implementation. This example maps the interface MessageService to its implementation EmailService.</li>
</ol>
<p>In plain terms: When I ask Guice to give me an instance of MessageService, it will give me an instance of EmailService.</p>
<p><em>But, how will it know to create an instance of EmailService</em>? We’ll see that later.</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MessagingModule</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AbstractModule</span> </span>{  @Override   protected <span class="hljs-keyword">void</span> configure() {    bind(MessageService.class).to(EmailService.class);  }}
</code></pre><p>Maybe we want more than one instance of MessageService in our project. At some places, we would want a SMSService to be associated with a MessageService, rather than an EmailService. In such cases, we use a binding annotation. To create a binding annotation, you will have to create two annotations like so:</p>
<pre><code>@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)public @interface Email {}
</code></pre><pre><code>@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)public @interface SMS {}
</code></pre><p>You need not know about the metadata annotations (@Target, @ Retention). If interested, please read this: <a target="_blank" href="https://github.com/google/guice/wiki/BindingAnnotations">https://github.com/google/guice/wiki/BindingAnnotations</a></p>
<p>Once we have the annotations with us, we can create two separate bindings which instruct Guice to create different instances of MessageService based on the BindingAnnotation (I think of it as a qualifier).</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MessagingModule</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AbstractModule</span> </span>{  @Override   protected <span class="hljs-keyword">void</span> configure() {   bind(MessageService.class).annotatedWith(Email.class)                             .to(EmailService.class);
</code></pre><pre><code>   bind(MessageService.class).annotatedWith(SMS.class)                             .to(SMSService.class);  }}
</code></pre><ol start="2">
<li><strong>Instance Binding:</strong> Binds a type to a specific instance</li>
</ol>
<pre><code> bind(Integer.class) .annotatedWith(Names.named(“login timeout seconds”)) .toInstance(<span class="hljs-number">10</span>);
</code></pre><p>One should avoid using .toInstance with objects that are complicated to create, since it can slow down application startup. You can use an @Provides method instead. In fact, you can even forget that we mentioned anything about Instance binding right now.</p>
<ol start="3">
<li><strong>@ Provides annotation</strong>:</li>
</ol>
<p>This is straight from Guice’s wiki, as it is fairly simple:</p>
<blockquote>
<p>When you need code to create an object, use an <code>@Provides</code> method. The method must be defined within a module, and it must have an <code>@Provides</code> annotation. The method's return type is the bound type. Whenever the injector needs an instance of that type, it will invoke the method.</p>
</blockquote>
<pre><code>bind(MessageService.class)
</code></pre><pre><code>.annotatedWith(Email.class)
</code></pre><pre><code>.to(EmailService.class);
</code></pre><p>is same as</p>
<pre><code>@Provides@Emailpublic MessageService provideMessageService() {  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> EmailService();}
</code></pre><p>where Email.java is a Binding annotation.</p>
<p>Dependencies can be passed to a method with this annotation which makes it extremely useful in real life projects. For example, for the code mentioned below, the injector will exercise the binding for the string parameter <strong><em>apiKey</em></strong> before invoking the method.</p>
<pre><code>@Provides @PayPalCreditCardProcessor providePayPalCreditCardProcessor(      @Named(<span class="hljs-string">"PayPal API key"</span>) <span class="hljs-built_in">String</span> apiKey) {  PayPalCCProcessor processor = <span class="hljs-keyword">new</span> PaypalCCProcessor();  processor.setApiKey(apiKey);  <span class="hljs-keyword">return</span> processor;  }
</code></pre><ol start="4">
<li><strong>@ Inject annotation</strong> (Just in Time binding): Whatever we covered up until now are called <em>explicit bindings.</em> If Guice, when trying to create an instance, does not find an explicit binding, it tries to create one using a Just-in-time binding.</li>
</ol>
<p>Guice can create these bindings by using the class’s <em>injectable constructor</em>. This is either a non-private, no-arguments constructor or a constructor with the <code>@Inject</code>annotation.</p>
<h3 id="heading-task">Task</h3>
<p>Now let’s move to the project we cloned from Github.</p>
<p>Like the examples in the <a target="_blank" href="https://medium.freecodecamp.org/demystifying-dependency-injection-49d4b6fe6536">previous article</a>, this maven project implements a BillingService which charges a PizzaOrder using a credit card and generates a Receipt.</p>
<p>The project structure is as follows:</p>
<p><strong>Interfaces</strong></p>
<ul>
<li>BillingService — charges an order using a credit card</li>
<li>CreditCardProcessor — debits some amount from a credit card</li>
<li>TransactionLog — logs results</li>
</ul>
<p><strong>Classes</strong></p>
<p>src</p>
<ul>
<li>CreditCard — entity representing a Credit Card</li>
<li>PizzaOrder — entity representing a Pizza order</li>
<li>Receipt — entity representing a receipt</li>
<li>RealBillingService implements BillingService</li>
<li>PaypalCreditCardProcessor implements CreditCardProcessor</li>
<li>BankCreditCardProcessor implements CreditCardProcessor</li>
<li>InMemoryTransactionLog implements TransactionLog</li>
<li>GuiceTest — Main class which uses BillingService</li>
<li>BillingModule — All Guice bindings go here</li>
<li>GuiceInjectionTest : Unit tests to check binding constraints</li>
</ul>
<p>The task here is to create Guice Bindings in the BillingModule such that the following constraints are satisfied:</p>
<ol>
<li>All implementations of BillingService should be bound to RealBillingService.</li>
<li>CreditCardProcessor interface annotated with @Paypal should be bound to PaypalCreditCardProcessor class.</li>
<li>CreditCardProcessor interface named with string “Bank” should be bound to BankCreditCardProcessor class.</li>
<li>BillingService instances returned by injector should have an instance of BankCreditCardProcessor as their dependency.</li>
<li>All implementations of TransactionLog should be bound to InMemoryTransactionLog.</li>
</ol>
<p>All five unit tests in GuiceInjectionTests should pass if the above conditions are satisfied. You should also be able to run the main method in GuiceTest.</p>
<p>To test correctness:</p>
<ol>
<li>run unit tests</li>
</ol>
<pre><code>mvn test
</code></pre><p>This should run the test file GuiceInjectionTests.java.</p>
<ol start="2">
<li>run the main file</li>
</ol>
<pre><code>mvn exec:java -Dexec.mainClass=<span class="hljs-string">"GuiceTest"</span>
</code></pre><p>This should execute the main class of the project, which does the end to end work of creating an order, processes payment using a credit card and generates a receipt.</p>
<p>You can comment if you have any questions and I will try answering them. Please note that there is no single correct answer for this exercise. DM me your solutions and I will add the answers to the repository. Or better still, send me a pull request :)</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Demystify Dependency Injection and see it in action with this quick intro ]]>
                </title>
                <description>
                    <![CDATA[ By Sankalp Bhatia Dependency Injection (DI) is a topic which I found a little difficult to grasp during my initial days as a software developer. I just could not find a good definition of the term. In this article, I’ve tried to put my understandings... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/demystifying-dependency-injection-49d4b6fe6536/</link>
                <guid isPermaLink="false">66c348eb0bafa8455505c6aa</guid>
                
                    <category>
                        <![CDATA[ dependency injection ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 15 Apr 2018 17:42:44 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*hnStARpFrN-7liCbeUKXRw.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Sankalp Bhatia</p>
<p>Dependency Injection (DI) is a topic which I found a little difficult to grasp during my initial days as a software developer. I just could not find a good definition of the term.</p>
<p>In this article, I’ve tried to put my understandings of it in fairly simple language. It is intended for people starting out with DI, or those who just want to get a little more insight.</p>
<h3 id="heading-what-is-dependency-injection"><strong>What is Dependency Injection?</strong></h3>
<p>First things first: what is it? Dependency Injection, like so much other software development jargon, is a fancy term for a rather simple concept.</p>
<p>The definition which I found most useful is:</p>
<p><strong><em>Dependency injection means giving an object its instance variables.</em></strong></p>
<p>That’s it. Providing (injecting) dependencies for a class. Simple right? Indeed.</p>
<p>Now, there are three ways of providing a class its dependencies in Java. All of them achieve…(coughs) Dependency Injection.</p>
<p>They are:</p>
<ul>
<li>Constructors</li>
<li>Setters</li>
<li>Directly setting public fields</li>
</ul>
<h3 id="heading-lets-see-dependency-injection-in-action">Let’s see Dependency Injection in action</h3>
<p>I have an application class named MyMessagePublisher which has a dependency on a certain EmailService class.</p>
<h4 id="heading-dependency-injection-using-constructor"><strong>Dependency Injection using Constructor:</strong></h4>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyMessagePublisher</span> </span>{    private EmailService emailService = <span class="hljs-literal">null</span>;        public MyMessagePublisher(EmailService emailService){        <span class="hljs-built_in">this</span>.emailService = emailService;    }}
</code></pre><p>See what the constructor is doing there? It is telling MyMessagePublisher to use the EmailService provided by it. The class instantiating MyMessagePublisher should provide (inject) an EmailService instance (using the constructor) to be used by MyMessagePublisher. Something like this:</p>
<pre><code>EmailService emailService = <span class="hljs-keyword">new</span> EmailService();MyMessagePublisher myMessagePublisher =                            <span class="hljs-keyword">new</span> MyMessagePublisher(emailService);
</code></pre><p>Good job, Constructor!</p>
<h4 id="heading-dependency-injection-using-setter"><strong>Dependency Injection using Setter:</strong></h4>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyMessagePublisher</span> </span>{    private EmailService emailService = <span class="hljs-literal">null</span>;    public MyMessagePublisher() {    }    public setEmailService(EmailService emailService) {        <span class="hljs-built_in">this</span>.emailService = emailService;    }}
</code></pre><p>What’s going on here? The class using MyMessagePublisher can now set the EmailService which they want to use. Something like this:</p>
<pre><code>MyMessagePublisher myMessagePublisher = <span class="hljs-keyword">new</span> MyMessagePublisher();myMessagePublisher.setEmailService(<span class="hljs-keyword">new</span> EmailService());
</code></pre><p>Good job, Setter!</p>
<h4 id="heading-dependency-injection-by-directly-setting-public-fields"><strong>Dependency Injection by directly setting public fields</strong></h4>
<p>Never do this!! If you have reached this far reading this article, I believe you know that this approach is evil.</p>
<h3 id="heading-benefits-of-dependency-injection"><strong>Benefits of Dependency Injection</strong></h3>
<p>I’ll start this section by explaining what we miss out on if we do not use DI.</p>
<p>Consider this code. I have defined the EmailService and MyMessagePublisher classes. MyMessagePublisher itself instantiates an EmailService object instead of using the DI techniques mentioned above.</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmailService</span> </span>{        public <span class="hljs-keyword">void</span> sendEmail(<span class="hljs-built_in">String</span> message, <span class="hljs-built_in">String</span> receiver){        System.out.println(<span class="hljs-string">"Email sent to "</span> + receiver);    }}
</code></pre><pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyMessagePublisher</span> </span>{    private EmailService emailService = <span class="hljs-keyword">new</span> EmailService();    public <span class="hljs-keyword">void</span> processMessages(<span class="hljs-built_in">String</span> message, <span class="hljs-built_in">String</span> receiver){        <span class="hljs-built_in">this</span>.emailService.sendEmail(message, receiver);    }}
</code></pre><p>The above code has some limitations:</p>
<ol>
<li>If EmailService initialization logic changes (it takes a constructor parameter to initialize), we would need to make changes to MyMessagePublisher class along with everywhere else in the codebase where we are using EmailService without DI.</li>
<li>It has tight coupling. Let’s say we want to move away from sending emails and instead start sending SMSs. We will then have to write a new publisher class.</li>
<li>This code is not testable. We will be sending emails to everyone while unit testing MyMessagePublisher class.</li>
</ol>
<p>This is the solution I propose:</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmailService</span> <span class="hljs-title">implements</span> <span class="hljs-title">MessageService</span> </span>{    @Override    public <span class="hljs-keyword">void</span> sendMessage(<span class="hljs-built_in">String</span> message, <span class="hljs-built_in">String</span> receiver) {        <span class="hljs-comment">//logic to send email    }}</span>
</code></pre><pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SMSService</span> <span class="hljs-title">implements</span> <span class="hljs-title">MessageService</span> </span>{    @Override    public <span class="hljs-keyword">void</span> sendMessage(<span class="hljs-built_in">String</span> message, <span class="hljs-built_in">String</span> receiver) {        <span class="hljs-comment">//logic to send SMS    }</span>
</code></pre><pre><code>public interface MessageService {    <span class="hljs-keyword">void</span> sendMessage(<span class="hljs-built_in">String</span> message, <span class="hljs-built_in">String</span> receiver);}
</code></pre><pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyMessagePublisher</span> </span>{    private MessageService messageService;        public MyMessagePublisher(MessageService messageService){        <span class="hljs-built_in">this</span>.messageService = messageService;    }        @Override    public <span class="hljs-keyword">void</span> processMessages(<span class="hljs-built_in">String</span> msg, <span class="hljs-built_in">String</span> rec){        <span class="hljs-built_in">this</span>.service.sendMessage(msg, rec);    }}
</code></pre><p>This implementation overcomes all three limitations mentioned above.</p>
<ul>
<li>EmailService (or MessageService) initialization logic moves to the module initializing MyMessagePublisher</li>
<li>We can move to a different implementation of MessageService which sends SMS without changing code in MyMessagePublisher</li>
<li>The code is testable. We can use a dummy implementation of MessageService while unit testing MyMessagePublisher</li>
</ul>
<p>Sweet. We have achieved DI using Constructors of our classes. Easy right? But there are some shortcomings here as well.</p>
<h3 id="heading-issues-with-vanilla-dependency-injection">Issues with Vanilla Dependency Injection</h3>
<p>When does this become a problem? <strong>When the code grows</strong>.</p>
<p>So what are the alternatives? <strong>Dependency Injection Containers</strong> (Spring, Guice, Dagger, and so on).</p>
<p>Let’s try to answer the questions above in more detail.</p>
<p>Consider the code below. We are designing an AllInOneApp which offers multiple services like booking movie tickets, recharging prepaid connections, transferring money, and online shopping.</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BookingService</span> </span>{    private SlotsManager slotsManager;    private MyMessagePublisher myMessagePublisher; <span class="hljs-comment">//Looks familiar?}</span>
</code></pre><pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AllInOneApp</span>  </span>{    BookingService bookingService; <span class="hljs-comment">// Class above    RechargeService rechargeService;    MoneyTransferService moneyTransferService;    ShoppingService shoppingService;}</span>
</code></pre><p>AllInOneApp needs four dependencies to be initialized. Let’s use vanilla Dependency Injection using Constructor here and instantiate the AllInOneApp class.</p>
<pre><code>public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span>[] args) {
</code></pre><pre><code>AllInOneApp allInOneApp = <span class="hljs-keyword">new</span> AllInOneApp(                <span class="hljs-keyword">new</span> BookingService(<span class="hljs-keyword">new</span> SlotsManager(),                                   <span class="hljs-keyword">new</span> MyMessagePublisher(                                              <span class="hljs-keyword">new</span> EmailService())),                 <span class="hljs-keyword">new</span> RechargeService(...),                 <span class="hljs-keyword">new</span> MoneyTransferService(..),                <span class="hljs-keyword">new</span> ShoppingService(...));
</code></pre><pre><code>}
</code></pre><p>This looks messy. Can we identify the problems here? A couple of them are:</p>
<ul>
<li>The class initializing AllInOneApp needs to know the logic to construct all the dependency classes as well. This is cumbersome when writing code in any decent sized project. Managing all these instances by ourselves is not what we want to do while writing business specific code.</li>
<li>Although I have seen people prefer this kind of DI, I personally believe this code is less readable as compared to this:</li>
</ul>
<pre><code>AllInOneApp myApp = SomeDIContainer.getInstance(AllInOneApp.class);
</code></pre><p>If all the components use DI, somewhere in the system some class or factory must know what to inject into all these components (AllInOneApp, BookingService, MessageService etc).</p>
<p><strong>This is where Dependency Injection containers come into picture</strong>. It is called a container and not a factory because the container often takes on more responsibility than just instantiating objects and injecting dependencies.</p>
<p>DI containers let us define what components are to be initiated and what dependencies to be injected in those components. We can also configure other instantiation features, like the object being a singleton or getting created every time it is requested.</p>
<p>I will be writing another article explaining the usage of one of the popularly used DI Containers, Google Guice, which will have a hands on practice section as well. I will update this story with it’s link soon. I will now leave you with this <a target="_blank" href="https://github.com/google/guice/wiki/GettingStarted">user guide</a> which is a good place to start.</p>
<p>Thank you for reading :)</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
