<?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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Barış Çakmak on Medium]]></title>
        <description><![CDATA[Stories by Barış Çakmak on Medium]]></description>
        <link>https://medium.com/@peacelighter?source=rss-7787081e5fdd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Or78akcvKebxq9p96uWvKA.png</url>
            <title>Stories by Barış Çakmak on Medium</title>
            <link>https://medium.com/@peacelighter?source=rss-7787081e5fdd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 12:48:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@peacelighter/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Composition Root and Service-Locator Pattern in Tuist’s µFeatures Architecture with Swinject and…]]></title>
            <link>https://peacelighter.medium.com/composition-root-and-service-locator-pattern-in-tuists-%C2%B5features-architecture-with-swinject-and-9ce8e5854d87?source=rss-7787081e5fdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ce8e5854d87</guid>
            <dc:creator><![CDATA[Barış Çakmak]]></dc:creator>
            <pubDate>Mon, 10 Oct 2022 14:47:28 GMT</pubDate>
            <atom:updated>2022-10-10T14:47:28.796Z</atom:updated>
            <content:encoded><![CDATA[<h3>Composition Root and Service-Locator Pattern in Tuist’s µFeatures Architecture with Swinject and Factory Libraries</h3><p>First of all, I would like to explain a bit about myself and how I am faced with such a specific issue that the article is going to be about.</p><p>I am Barış Çakmak and I have been started learning iOS/Swift Development 9 months ago. Currently, I have no job experience in iOS Development and I am a big fan of the Software Architect part of iOS Development.</p><p>— How I am faced with a Tuist?</p><p>I graduated from a Bootcamp. UI Architectural Pattern that I used there was the VIPER pattern. After understanding and getting the know-how about the fundamentals and testable structure. It had come to write Unit Tests. After the big refactor, I have written the Unit tests for my Bootcamp Project.</p><p>The only thing that is missed on my checklist was getting familiar with the Modular App Structure and facing the problems of the Scalable App. At that time, I would have chosen SPM or any other Dependency Management Tool but I came across the Tuist tutorial from the <a href="https://www.youtube.com/watch?v=wlGInAIRGiU">NSIstanbul Meeting</a>. Thanks to Mustafa Yusuf and Anıl Taşkıran for their tutorial about how to create a Tuist Project, problems of the Modular App Structure/SPM, and the explanation about the Tuist’s API.</p><p>It was time to implement the Tuist to my Bootcamp Project. Implementation had done with a big problem which is Circular Dependency. Since modules were created outside with static functions, Modules were depending on each other’s concrete types.</p><p>At that time, another <a href="https://www.youtube.com/watch?v=UKs5HYlTXOM">NSIstanbul Meeting</a> solved my problem. This session explains how the µFeatures Architecture is implemented by Trendyol Team. Therefore, I have refactored my app again with the DependencyEngineKit that the session is focused on and explained it.</p><p>The project was working without any problem and µFeatures Architecture is implemented without any problem. However, implementation and depending on DependencyEngineKit itself felt a bit strange to me.</p><p>So I have decided to research about Dependency Injection and Dependency Inversion Principle.</p><p>This article explains the basics of Composition Root, and Service-Locator and shows you how to implement both Patterns along with the creating modules with stencils that I have written for this article.</p><h3>Part 0: Getting Familiar with the Service Locator and Composition Root Pattern</h3><h4>Service-Locator Pattern</h4><p>Service-Locator is usually called an anti-pattern and not considered as Dependency Injection. The reason why is the class itself is responsible to create/calling the dependencies. However, In Composition Root, there is no such responsibility or knowledge about the creation/calling of the instance/dependency except from the entry-point of the App.</p><p>This is why I write this as an article, my tuist project is using the Service-Locator pattern to inject and create the dependencies.</p><p>But, what is a Service-Locator in Swift Language? Give me an example…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPOtf5ZgWs0wlkyI71BGyQ.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/b85c316331b137b6377b75b7a2038ccd">Service Locator</a></figcaption></figure><p>This is the basic Service-Locator implementation that registers the given type and resolves the desired type requested from a dictionary.</p><p>To use this Service, we can call the shared instance and register some protocol declarations in general. This can be done at the AppDelegate or any other places but to compare with Composition-Root and not have crashes we will inject the dependencies at App Level in both Examples. Of course, you can inject wherever you want and resolve it without any problem if you know what you are doing.</p><p>Let’s register some not existing Protocol and resolve it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-HQTt0ytRKECm-XTXz2Kw.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/702a3f1a5ec2b7a9530bd958d206e375">Service Locator Usage</a></figcaption></figure><p>Hey, it seems a normal Dependency Injection, isn’t it? Well, until this point, there is no problem about the structure but the thing that makes this as a Service-Locator is “you must depend on the Service-Locator itself in every module you are using”.</p><p>For example, if Module A needs Module B Interface, and Module B needs Module A Interface as Tuist’s µFeatures Architecture recommends this usage, you have to register the dependencies at App Level and resolve with using ”Service-Locator Container” at Modules. That means you have to add Service-Locator Container to every Module. I will show the real Dependency Graphs on Part 2 with my old Tuist Project..</p><p>Briefly, If a module itself accesses the Dependency Container directly, that means we are using Service-Locator Pattern</p><p><strong>— Pros</strong></p><ul><li>We can add whatever dependency to inject and remove at runtime.</li><li>We can replace, delete or update the dependency at runtime.</li><li>It is easy to understand and implement.</li></ul><p>— <strong>Cons</strong></p><ul><li>You have to make sure that before instantiating, we need to setup the Dependency Container properly.</li><li>All Components need to depend on Service-Locator which is a Singleton.</li><li>We may need to mock Service Locator with Mock Dependencies but VIPER can solve this issue easily.</li><li>Dependencies are hidden inside the class since it will be resolved at runtime.</li></ul><h4>Composition Root Pattern</h4><p>Composition Root is a centralized place where you instantiate and compose all the modules together.</p><p>This approach must be done very close to the Application Entry Level which is a main in iOS Applications.</p><p>The reason why Composition Root is recommended way of structuring the Modular App is centralizing and composing all the dependencies in one place reduces the complexity of the App and the number of dependencies in Dependency Graph in general.</p><p>Rule of the composition root is “modules should not depend on Composition Root(main)”. This sounds familiar to you? Yes it is. Service-Locator Pattern violates this rule and this is why it is called “Anti-Pattern” often.</p><p>To implement the Composition Root, the modules must be decoupled very well to follow the Dependency Inversion Principle from SOLID Principles. Otherwise, implementing the Composition Root seems impossible or wrong.</p><p>How can we know how long our dependency will be alive? Since we do not have any access to the Composition Root from anywhere else, the Dependency Container and Object Graph/Scope is responsible to decide the dependency’s lifetime.</p><p>We can use the same ServiceLocatorContainer class example from above but if we depend on this class then we need to understand that it becomes Service-Locator.</p><h3>Part1: What is an µFeatures Architecture?</h3><p>uFeatures is an architectural approach to structure Apple OS applications to enable scalability, optimize build and test cycles, and ensure good practices in your team. Its core idea is to build your apps by building independent features that are interconnected using clear and concise APIs.</p><p>uFeatures Architecture is explained above in <a href="https://docs.tuist.io/building-at-scale/microfeatures/">Tuist’s Documentation</a>. As a strategy below that is referenced from Tuist’s documentation, we are going to only focus on the “Module Interface” idea and the “Dependencies between µFeatures” part of the Documentation.</p><p>Module Interface idea is adding an interface to a module that will isolate the module by calling from the concrete type of modules. By achieving this approach, our app ends up with horizontal dependency graphs which will decrease the build time significantly.</p><p>To deep-dive and fully understand the strategy you can either watch this <a href="https://www.youtube.com/watch?v=sZuI6z8qSmc">video</a> from Spotify or an <a href="https://swiftrocks.com/reducing-ios-build-times-by-using-interface-targets">article</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*mFj75JBskJRnMrtSSO58ig.png" /><figcaption>Modules depending on each other’s interfaces</figcaption></figure><h3>Part 2: Service-Locator on an Existing Tuist Project</h3><p>To make everything clear, we will look a the real example from my Project. To follow Service-Locator pattern and uFeatures Architecture, our modules depend on the Dependency Container and Modules only depend other’s ModuleInterfaces.</p><p>Let’s Look at the RestaurantModule from my <a href="https://github.com/baris-cakmak/TechCareerGraduationProject-VIPER">Tuist Project</a>. RestaurantModule depends on its Interface along with the other Module’s interface which is a HomeModuleInterface in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1fyehAyvKgdgBBMUD0hg4g.png" /><figcaption>Restaurant Module Dependency Graph</figcaption></figure><p>Zoom left of the graph, you can see the DependencyManagerKit. Let’s look at the Source files of the DependencyManagerKit which are taken from the <a href="https://www.youtube.com/watch?v=UKs5HYlTXOM">NSIstanbul Session</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ksHERv7WYEqlIG1EDwGJGA.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/86e62b2732e7d8110e0097d3f9155720">Dependency Engine</a></figcaption></figure><p>We have Singleton DependencyEngine. Singleton does not mean that we have Service-Locator Pattern. Let’s look at the RestaurantRouter to how we use the decoupled module interfaces and create the modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CBhRQYDxuFad853lrEfrHw.png" /></figure><p>We are using the Property Wrapper that is called Dependency type and let’s look at the implementation detail of the Dependency Property Wrapper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*dLsziUdcrnThYTZtwvgisQ.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/0a9e705c3fbe1a7af5c7ff18637b5ca8">Dependency Property Wrapper</a></figcaption></figure><p>Whenever we use either set or read the “Value”, we use the single instance of DependencyEngine. That means we depend on the container from every modules that we are in.</p><p>Since we depend on DependencyEngine for every module, we follow the Service-Locator pattern to register and resolve the dependencies.</p><h3>Part 3: Service-Locator Tutorial with Factory Library on a Tuist Project</h3><p>I have chosen the <a href="https://github.com/hmlongco/Factory">Factory Library</a> whose creator is Michael Long. He is also a creator of another popular Dependency Injection Library that is called <a href="https://github.com/hmlongco/Resolver">Resolver</a>.</p><p>I was looking for a Compile-Time safety Dependency Injection Library and there were limited options such as <a href="https://github.com/uber/needle">Needle</a> from Uber Team and <a href="https://github.com/scribd/Weaver">Weaver</a>. I was not the only person that needs and looking for a compile-time safety DI Library. The creator of the Resolver Library has written this Library lately because of this.</p><p>The features of the Factory Library are quite well-thought but when it comes to decoupled modules or Modular App in general, Library struggles in terms of referencing the Dependency Container. This is why we are using this library to follow Service-Locator Pattern with its newly added APIs lately.</p><p>We can use the Factory with Property Wrapper or Call the Container Directly. Let’s register some Dependencies and resolve them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*IbDtYUTot0p50FKnWppfdQ.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/f8155181c9ae851780501a2d8d8b73ee">Registration of the Dependency by Extending the Container</a></figcaption></figure><p>After the registration, we can call the dependency with two given API option below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*EzEDVOcVVd1mMkySTQQUVw.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/505c9d876c84c7a93bcbc5ed60df1c89">Resolving the Dependencies</a></figcaption></figure><p>If you need more details about the Library and API usage, please refer to Github Link that is attached above.</p><p>After getting familiar with the Factory Library and the Service-Locator Pattern, we can implement this to Tuist with Decoupled Module Strategy.</p><p>Since you may not familiar with the Tuist, I have created some CoreModules, Kits, and Helper Classes. The only thing that has been missed is the “Modules”. Do not worry, I have also created stencils for both Factory and Swinject Branches.</p><p>Enough talk, open Factory Branch and move to the Project Directory from terminal to create Modules and fetch Factory dependency as an external dependency.</p><p>Run the command below to install the Factory Library.</p><pre>tuist fetch</pre><p>After the fetching the Factory Library, its time to create RootModule. This RootModule is not a part of the Horizontal Dependency Strategy for the faster builds. It is only for you to understand the structure of the App.</p><pre>tuist scaffold module --name Root</pre><p>If everything goes well, you are able to create the project with given tuist command below.</p><pre>tuist generate</pre><p>Let’s Focus on RootModule. View, Presenter, and Interactor files are basic boilerplate Viper files that you can look at it if you are not familiar with the VIPER.</p><p>Router is a bit different, to not get confused between normal RouterInterface and ModuleInterface, I have used two different Protocols.</p><p>In RootModuleInterface, we can see the following generated code below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5Wwz09Q7AXQdnZC57Co4Q.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/c70c831f9bd58d83d3618e5cf6f6a614">Root Module Interface</a></figcaption></figure><p>The stencil has created a module with injected nil parameters. Since we do not want ModuleInterfaces to depend on anything else, and we can inject the Concrete type by calling the InterfaceModule, it follows Service-Locator quite well.</p><p>Let’s do the logic that is explained above.</p><p>Open App’s Source Folder and Create new Swift file that is called ServiceLocatorContainer. Let’s Write the Following code that is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*rnLINq283lXO59_ne-KViA.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/bb90c6506ffa52172782db0321899f03">Registering the Root Module at App Level</a></figcaption></figure><p>We both reference the RootModule and RootModuleInterface to inject the service/dependency with the Concrete type to use it on other Modules.</p><p>Now, open AppDelegate.swift, and lets inject the dependencies and resolve RootModule to see if everything works as we expected.</p><p>Updated AppDelegate code is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvSS29wRlZOCjVGKoQUS8Q.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/75a2529176a70461e8aa9fed1e10d2d6">Updated AppDelegate with RootModule</a></figcaption></figure><p>Now we have the following output which we expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*kMlm3dFM5zounM-uQ8sHyA.png" /></figure><p>Now we have seen Service-Locator, VIPER, and some Tuist options. It’s time to implement the Module A -&gt; Module B Interface, Module B -&gt; Module A Interface logic.</p><p>We will create 2 two modules which are named Home and Login. Both of them will depend on JsonPlaceHolderKit which also depends on my basic Core Network Layer.</p><p>Let’s go.</p><pre>tuist scaffold module --name Home</pre><pre>tuist scaffold module --name Login</pre><p>After creations, let’s edit the Manifest files with</p><pre>tuist edit</pre><p>Open the RootModule’s Project.swift and update the code with Home and Login Module Interfaces which is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJmSDchYktYvBrrgV-CXWg.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/f957436a7c04a2fb9451593c18c2de7f">Updated Root Module Manifest</a></figcaption></figure><p>Update the Home and Login Module’s Project.swift files with the codes written below to depend on each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKJne-ONiuawYNc78pAlgg.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/0c3ba19dbdb5446a55802b58034ef688">Updated Home and Login Module Manifests</a></figcaption></figure><p>And for the last part, Add Home and Login module to the App’s Project file by the following code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ryW1HQqOh30vxslhakcIaQ.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/d3e5a78e21c54e67c6586959f6082461">Updated App’s Manifest</a></figcaption></figure><p>After specifying the dependencies, let’s look at the Dependency Graph with the command below.</p><pre>tuist graph</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*RIUdT9ZpsxsGRLrg7R9mwg.png" /><figcaption>Dependency Graph with Updated Dependencies</figcaption></figure><p>Yayyy!! Now we have cool horizontal dependency tree which decreases the build time significantly.</p><p>Let’s also add JsonPlaceHolderKit to the HomeModule and LoginModule to use it on Interactor with this.</p><pre>AllDependencies.jsonPlaceHolderKit</pre><p>Dependency Graph becomes..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*mJr4iSKx3FMIyM5XubHlQg.png" /><figcaption>Updated Dependency Graph with JsonPlaceHolderKit Injection</figcaption></figure><p>Run the project by “tuist generate” command.</p><p>Let’s look at the JSONPlaceholderService.swift file. We have a private access level of concrete type of JsonPlaceholderService since we only need Container reference because of the Service-Locator Pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHsk0K5AaAv_H0g8m0nTjg.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/e20b38364b2162a30ea774f5e2cd0e3c">JsonPlaceHolderKit Service Injection</a></figcaption></figure><p>I have called this reference and injected it into both Home and Login Interactors to fetch some Posts. The reason why we duplicate the calling is we will look at the memory graphs in Composition Root to see the differences.</p><p>Before navigating from the modules, do not forget to inject in ServiceLocatorEngine!!.</p><p>Now Let’s navigate to the Home screen from Root after 1 second and to Login from Home and Home from Login to create infinite navigation to see if everything goes well.</p><p>One of the route example is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mx0E5o7Zd2DZSNc6ohkc9A.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/4d9655ae3252c8107978043849799b97">Root to Home Updated RootRouter</a></figcaption></figure><p>After various navigations, let’s look at the memory graph to see if everything is expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*FfsxHHK6lYa1kJ-CyOrn_w.png" /><figcaption>Memory Graph of Finished Project</figcaption></figure><p>Yessss!!. We have successfully finished our Service Locator Tuist Project with Factory Library. To see the final project. Look at the Factory-Finished Branch from this <a href="https://github.com/baris-cakmak/Tuist-DependencyInjection-Medium/tree/Factory-Finished">link</a>.</p><h3>Part 4: Composition Root Tutorial with Swinject Library on a Tuist Project</h3><p><a href="https://github.com/Swinject/Swinject">Swinject</a> is well written Dependency Injection Library that has great options to implement on a project.</p><p>Let’s see some basic registration and resolving from Swinject.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlXUwwceKSqts5yA4pSDrQ.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/f6863011a61273d788f7df84e1605bad">Swinject Basic Registration</a></figcaption></figure><p>After registrations, we can resolve dependencies in an example below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wjpaIuWvJl4TVsRj8nivvQ.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/f5b8a6cfb14029774accbdc0858eb64d">Swinject Basic Resolving</a></figcaption></figure><p>This is the basic usage of the Swinject, in our Tuist Demo App, we will use some other features from the Swinject library whenever we need them.</p><p>You know how the Tuist and our strategy work from Service-Locator Part. Therefore, We will use the same ideas again.</p><p>We need to fetch the Swinject Dependency Remotely. Run the following command on the project’s directory.</p><pre>tuist fetch</pre><p>Now, it is time to create Root, Home, and Login Modules with Stencils like below</p><pre>tuist scaffold module --name Root</pre><pre>tuist scaffold module --name Home</pre><pre>tuist scaffold module --name Login</pre><p>We have experienced in terms of adding modules as target dependency in the Service-Locator part. So let’s update the target dependencies as we have done in Part 3.</p><p>After adding all Target Dependencies, the dependency graph should be something similar to the following image by running the command below</p><pre>tuist graph</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*qdCQmUt7Lk_Lby5oev1ZvA.png" /><figcaption><a href="https://github.com/baris-cakmak/Tuist-DependencyInjection-Medium/blob/Swinject-Finished/TuistSwinjectDemo/graph.png">Swinject Final Dependency Graph</a></figcaption></figure><p>The dependency graph is ready to inject our dependencies. In this example, we have a folder that is called Component. This folder will include dependencies to inject from the Entry Point of our App. Let’s analyze the dependencies and create some Dependencies in Component files.</p><pre>RootComponent -&gt; HomeModuleInterface, LoginModuleInterface</pre><pre>HomeComponent -&gt; LoginModuleInterface, JsonPlaceHolderInterface</pre><pre>LoginComponent -&gt; HomeModuleInterface, JsonPlaceHolderInterface</pre><p>Let’s focus on RootComponent to follow a similar approach in other Component files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*ex7HJjLzRzlcbNvyUW37cQ.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/670548b3a3904f8339f42d47add5baca">Root Component with Constructor Injection</a></figcaption></figure><p>If you are finished implementing dependencies to the Components files, let’s move on to the injection part.</p><p>Create a Swift file that is called DependencyContainer on App’s Sources Folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vvj0zxEbCP7Tru73ixpr-w.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/618822a6a49c4995f1f8acb64ef404d4">Singleton Dependency Container</a></figcaption></figure><p>We have a single instance of Container but it will not be accessed from any other modules as we explained before as a rule.</p><p>Let’s extend our DependencyContainer Class with a function that is called injectDependencies and create another private func that is called registerRootModuleDependencies and call it on injectDependencies shown below. After injecting other modules and kits, we will see a crash on our app which is shown below. To follow until this point, you can look at this <a href="https://github.com/baris-cakmak/Tuist-DependencyInjection-Medium/commit/1dacce2228d4ce14fa2d61909ebf07ace997fb61">commit</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2ngiOE9ox9vsJfBXgP2Eg.png" /><figcaption>Circular Dependency Error</figcaption></figure><p>It is quite normal to have this error. Even our modules do not depend on each other, one of the modules must be registered before its registration.</p><p>Besides that, we keep xxxComponent reference on Routers. If we do not move on to any other modules or so, we end up registering the module on memory.</p><p>Aww! Service-Locator has advantages on registering and resolving somewhere at runtime right? Do not worry, we use Swinject because of its wide API options.</p><p>What if we inject our dependencies Lazily(delayed) and it only references on memory when it is called? It sounds very well right? Also, if we have more than 1000 Dependencies, registering all dependencies by Service-Locator and Lazy Injected Composition Root can affect the launch time? Maybe that can be analyzed on another Article.</p><p>Another question can be asked as “If our apps have houndreds or thousands of components to be injected, would it be a problematic to register all of the components event its lazily injected?”. We can create some helper classes to solve this problem or Swinject has variety of options such as <a href="https://github.com/Swinject/Swinject/blob/master/Documentation/Assembler.md">Assembler</a> to have different strategies. Anyway, let’s move on to our problem solving..</p><p>To use Lazy Injection, Swinject has a simple API that you can look at at this <a href="https://github.com/Swinject/Swinject/blob/master/Documentation/DelayedInjection.md">link</a> and the below example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r063TTsEncj_GX_63HHyVw.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/06c0e6d3ce0192d0d76b1010036d9bce">Lazy Injection of Modules</a></figcaption></figure><p>You can refer to the dependencies that are converted to Lazy with this <a href="https://github.com/baris-cakmak/Tuist-DependencyInjection-Medium/commit/ca80fe62691d7a2c08311804d31dda86f0a66792">commit</a>.</p><p>After changing all module dependencies with the Lazy ones, App works perfectly fine.</p><p>Now it is time to implement infinite navigation that we have done in Service-Locator part to look everything is fine. You can also refer to this implementation from this <a href="https://github.com/baris-cakmak/Tuist-DependencyInjection-Medium/commit/6f2dd976f771cab238add87553b3c8d1e96a5964">commit</a>.</p><p>Navigation to another module can be done with the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KVloBEDU8Y060A6igLWKDg.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/da89b1d4e73b0bab2bda189fe35e4902">Root to Home Navigation</a></figcaption></figure><p>After some infinite navigation, let’s look at the memory graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*HrvFux7ulKe0RYEuIbvSNw.png" /><figcaption>Memory Graph with Object Graph Scope</figcaption></figure><p>Heyy!! why we have only one Router for each Module. We would accept JsonPlaceholder Object numbers equal to module numbers since it is not registered Lazily but it is also seems one instance.</p><p>After looking at some objects at Swinject section, you will see some memory graph something like this below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G9VbDpL2OPer7XDfDtZEWw.png" /><figcaption>Memory Graph of Some Modules</figcaption></figure><p>When we refer to the ObjectScopes section of Swinject <a href="https://github.com/Swinject/Swinject/blob/master/Documentation/ObjectScopes.md">documentation</a>, we will see that the default object scope is Graph which is explained as</p><p>“With ObjectScope.graph, an instance is always created, as in ObjectScope.transient, if you directly call resolve method of a container, but instances resolved in factory closures are shared during the resolution of the root instance to construct the object graph.”</p><p>So this explains what is a GraphStorage. If we want to create one instance at every attempt of resolving, we can update the registration with transient scope as shown below. You can refer to all changes in terms of ObjectScope with this <a href="https://github.com/baris-cakmak/Tuist-DependencyInjection-Medium/commit/dca165409fbef13dba5f22832221a83162eaae8d">commit</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OkHKmWxwKT2nZ7LrN2a7Ng.png" /><figcaption><a href="https://gist.github.com/baris-cakmak/c0f9ca159882f2a17df806f48869d94c">Registering RootModuleInterface Dependencies in Transient Scope</a></figcaption></figure><p>Let’s implement JsonPlaceHolderService to Home and Login Module Interactors and look at the memory graph for the last time</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*2FhIImhj8bGXGTYklgFnBQ.png" /><figcaption>Final Memory Graph of Swinject Project</figcaption></figure><p>Yayy! We fully understand the differences between Composition Root and Service-Locator Patterns and implementation.</p><p>You can check the final version at the <a href="https://github.com/baris-cakmak/Tuist-DependencyInjection-Medium/tree/Swinject-Finished">Swinject-Final branch</a>.</p><h3>Conclusion</h3><p>We have both implemented Service-Locator and Composition Root Patterns on a Modular App. Both implementations can be used without any problem.</p><p>Service-Locator can be error-prone to inject our Dependencies.</p><p>Composition Root brings another principle to make our App’s structure a good way. Dividing the Dependencies and instantiation strategy can improve App’s performance significantly.</p><p>Service-Locator is often called an Anti-Pattern but if you know about what you are doing it does not seem dangerous with good maintenance.</p><p>Service-Locator hides the class dependencies. Therefore, it can cause run-time errors.</p><p>Nature of the Factory library provides clear usage because we extend our Containers inside Kits and Modules which use this Kits has reference to the specific dependency extension. This can be useful since we do not know dependencies inside the class, it restricts us with by some options that we have implemented.</p><p>In Service-Locator, we can resolve, register, update or remove our Dependencies at runtime easily. However, In Composition Root, we need to specify the object’s lifetime with ObjectScope or Dependency Containers.</p><p>This topic is a bit controversial. I highly recommend to watch this <a href="https://www.youtube.com/watch?v=RlfLCWKxHJ0">Google Tech Talk</a> that creator of AngularJS explains the Service-Locator.</p><p>Composition Root with Swinject provides object scopes that we can control the lifetime of the Dependency on a project at App Level.</p><p>To understand why we need Composition Root Pattern in our Apps, I recommend to watch Essential Developer’s this <a href="https://www.youtube.com/watch?v=cnHo2-gxqIQ">Podcast session</a>.</p><p>Thanks you for your reading. You can reach me on <a href="https://twitter.com/peace_lighter">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ce8e5854d87" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>