<?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 Berkay Yaman on Medium]]></title>
        <description><![CDATA[Stories by Berkay Yaman on Medium]]></description>
        <link>https://medium.com/@ymnberkayy?source=rss-e0d13daeca06------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cOQPrvsQqSqkduC0</url>
            <title>Stories by Berkay Yaman on Medium</title>
            <link>https://medium.com/@ymnberkayy?source=rss-e0d13daeca06------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 08:26:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ymnberkayy/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[SwiftUI Dependency Injection]]></title>
            <link>https://medium.com/@ymnberkayy/swiftui-dependency-injection-8c46dedd88ba?source=rss-e0d13daeca06------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c46dedd88ba</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Berkay Yaman]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 11:45:04 GMT</pubDate>
            <atom:updated>2026-02-11T11:45:04.621Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzp3kz3o0eTeGCmTWyf78g.png" /></figure><h3>Managing Dependencies in SwiftUI: A Practical Guide Without Third-Party Libraries</h3><p>As my SwiftUI app grew, I realized that managing dependencies in my ViewModels had become complicated , I had reached a point where I could no longer control my existing dependencies of application.</p><p>The problems were clear, especially when I wanted to test code. I needed to modify the view model just to test it.</p><h4>Beginning: Direct Instantiation in View</h4><p>The application had a structure like this in the initial stages. View model gives its dependency via the initializer , the service was generated directly within the view.</p><pre>protocol UserServiceProtocol {<br>    func fetchUser() async throws -&gt; User<br>}<br>class UserService: UserServiceProtocol {<br>    func fetchUser() async throws -&gt; User {<br>        //API Call<br>    }<br>}<br><br>@MainActor<br>class UserViewModel: ObservableObject {<br>    let service: UserServiceProtocol<br><br>    init(service: UserServiceProtocol) {<br>        self.service = service<br>    }<br>}<br><br>struct UserView: View {<br>    @StateObject private var viewModel =<br>        UserViewModel(service: UserService())<br><br>    var body: some View {<br>            Text(&quot;User View&quot;)<br>     }<br>}</pre><p>The code was working, but the same service was being repeated in different views, making it difficult to use mocks in test scenarios, and tracking where dependencies were being generated became increasingly complex. The main issue was that the services were being unnecessarily duplicated, making code maintainability and testability difficult.</p><h4>First Improvement with Factory Pattern</h4><p>In this situation, what I did was pull the View models into a central structure and generate them there. I defined a simple factory for this.Instead of directly generating UserViewModel view was giving its dependency via this factory. Thus, the generating of services was centralized in a single location.</p><pre>final class ViewModelFactory {<br><br>    static func makeUserViewModel() -&gt; UserViewModel {<br>        let service = UserService()<br>        return UserViewModel(service: service)<br>    }<br>}<br><br>struct UserView: View {<br>    @StateObject private var viewModel =<br>        ViewModelFactory.makeUserViewModel()<br>    <br>    var body: some View {<br>        Text(&quot;User View&quot;)<br>    }<br>}</pre><p>This approach seemed clean first.</p><h4>The limits of Factory Pattern</h4><p>This factory approach was enough when the application consisted of only a few screens. However, as new screens are added, Factory class started to grow steadily. Each new screen meant a new makeXViewModel() function and within these functions, how and in what configuration services were created was becoming increasingly complex.</p><pre>final class ViewModelFactory {<br><br>    func makeUserViewModel() -&gt; UserViewModel {<br>        UserViewModel(service: UserService())<br>    }<br><br>    func makeProfileViewModel() -&gt; ProfileViewModel {<br>        ProfileViewModel(<br>            userService: UserService(),<br>            analyticsService: AnalyticsService()<br>        )<br>    }<br><br>    func makeSettingsViewModel() -&gt; SettingsViewModel {<br>        SettingsViewModel(<br>            configService: ConfigService(),<br>            analyticsService: AnalyticsService()<br>        )<br>    }<br>}</pre><p>At this point, 2 main problem began to emerge.</p><p>Firstly, the lifecycle of dependencies was uncontrollable; the same service was being recreated repeatedly in some places, while in others it remained isolated when it should have been shared.<br>The second issue was testability. Because view model generation relies entirely on static methods, writing tests with mock services either became difficult or temporary solutions were created to make the code more flexible.</p><h4>Container+Factory Approach: Control lifecycle</h4><p>As the application grew, I realized the problem wasn’t so much about creating objects, but rather about their lifecycle and sharing. This led me to use Dependency Injection Containers instead of a factory structure.</p><pre>final class AppDependencyContainer: ObservableObject {<br><br>    // shared services throughout the entire application lifecycle<br>    let userService: UserServiceProtocol<br>    let analyticsService: AnalyticsServiceProtocol<br><br>    init() {<br>        self.userService = UserService()<br>        self.analyticsService = AnalyticsService()<br>    }<br><br>    // generating view model<br>    func makeUserViewModel() -&gt; UserViewModel {<br>        UserViewModel(service: userService)<br>    }<br><br>    func makeProfileViewModel() -&gt; ProfileViewModel {<br>        ProfileViewModel(<br>            userService: userService,<br>            analyticsService: analyticsService<br>        )<br>    }<br>}</pre><p>This structure, defined as an ObservableObject , works seamlessly with SwiftUI’s lifecycle and created once at application’s entry point and shared throughout the entire view hierarchy.</p><p>Thus, the scattered and static object generation of the factory approach is replaced by a lifecycle-managed, readable, and centralized object graph.</p><p>It becomes clear and controllable when services are created, how many times they are generated, and which view models share them.</p><h4>Container+Factory Positioning</h4><p>A container is not a structure that is frequently recreated like views, Instead, there should be a central component that lives on throughout the application, managing the lifecycle of dependencies . Therefore, the container’s entry level of access, accessible only once, is approach.</p><pre>@main<br>struct MyApp: App {<br><br>    @StateObject<br>    private var container = AppDependencyContainer()<br><br>    var body: some Scene {<br>        WindowGroup {<br>            RootView()<br>                .environmentObject(container)<br>        }<br>    }<br>}</pre><p>The use of @StateObject is a critical detail here. SwiftUI frequently recreates views; however, objects created with @StateObject are unaffected by these redraws. This ensures the dependency container remains independent of the UI lifecycle, preventing the need to recreate services or shared dependencies.</p><p>Injecting the container to the view as an @EnvironmentObject makes access to dependencies both centralized and consistent. Views now only request the view models they need from the container.</p><h4>Using Container+Factory Inside View</h4><p>The container is passed from the parent view to the child view as an init parameter. The child view then uses this container to create its own ViewModel using @StateObject.</p><pre>struct ParentView: View {<br>    @EnvironmentObject var container: AppDependencyContainer<br>    <br>    var body: some View {<br>        UserView(viewModel: container.makeUserViewModel())<br>    }<br>}<br><br>// Child<br>struct UserView: View {<br>    @StateObject private var viewModel: UserViewModel<br>    <br>    init(viewModel: UserViewModel) {<br>        _viewModel = StateObject(wrappedValue: viewModel)<br>    }<br>    <br>    var body: some View {<br>        Text(viewModel.userName)<br>    }<br>}</pre><p>From this point on, we can prevent the view from knowing the entire container by adding some extensions to the container.</p><pre>protocol UserViewDependency {<br>    func makeUserViewModel() -&gt; UserViewModel<br>}<br><br>extension AppDependencyContainer: UserViewDependency {<br>    func makeUserViewModel() -&gt; UserViewModel {<br>        UserViewModel(service: userService)<br>    }<br>}<br><br>struct UserView: View {<br>    @StateObject private var viewModel: UserViewModel<br>    <br>    init(viewModel: UserViewModel) {<br>        _viewModel = StateObject(wrappedValue: viewModel)<br>    }<br>}<br><br></pre><h4>Testability</h4><p>Actually this subject doesn’t rely with DI but while I write, I want to attention to testability. To briefly summarize we depend on protocols instead of concrete types, we can easily inject mock services for testing. No need to modify production code or create complex test setups.</p><pre>// Mock Service<br>final class MockUserService: UserServiceProtocol {<br>    var mockUser = User(name: &quot;Test User&quot;, email: &quot;test@example.com&quot;)<br>    var shouldFail: Bool = false<br>    <br>    func fetchUser() async throws -&gt; User {<br>        return mockUser<br>    }<br>}<br>// Test<br>@MainActor<br>final class UserViewModelTests: XCTestCase {<br>    <br>    func test_fetchUser_success() async {<br>        let mockService = MockUserService()<br>        let viewModel = UserViewModel(service: mockService)<br>        <br>        await viewModel.fetchUser()<br>        <br>        XCTAssertEqual(viewModel.userName, &quot;Test User&quot;)<br>    }<br>    <br>    func test_fetchUser_failure() async {<br>        let mockService = MockUserService()<br>        mockService.shouldFail = true<br>        let viewModel = UserViewModel(service: mockService)<br>        <br>        await viewModel.fetchUser()<br>        <br>        XCTAssertNotNil(viewModel.error)<br>    }<br>}</pre><h4>Real World Scenario</h4><p>Let’s see how this pattern scales with navigation. The coordinator handles routing while each view receives only its required dependency.</p><pre>struct AppCoordinator: View {<br>    @EnvironmentObject var container: AppDependencyContainer<br>    @State private var path = NavigationPath()<br>    <br>    var body: some View {<br>        NavigationStack(path: $path) {<br>            DashboardView()<br>                .navigationDestination(for: Screen.self) { screen in<br>                    switch screen {<br>                    case .userProfile:<br>                        UserProfileView(viewModel: container.makeUserProfileViewModel())<br>                    case .settings:<br>                        SettingsView(viewModel: container.makeSettingsViewModel())<br>                    case .analytics:<br>                        AnalyticsView(viewModel: container.makeAnalyticsViewModel())<br>                    }<br>                }<br>        }<br>    }<br>}</pre><p>In this structure, each view only knows the dependency protocol it needs.</p><pre>protocol UserProfileDependency {<br>    func makeUserProfileViewModel() -&gt; UserProfileViewModel<br>}<br><br>extension AppDependencyContainer: UserProfileDependency {<br>    func makeUserProfileViewModel() -&gt; UserProfileViewModel {  <br>          return UserProfileViewModel(<br>            userService: userService,<br>            analyticsService: analyticsService<br>        )<br>}<br><br>struct UserProfileView: View {<br>    @StateObject private var viewModel: UserProfileViewModel<br>    <br>    init(viewModel: UserProfileViewModel) {<br>        _viewModel = StateObject(wrappedValue: viewModel)<br>    }<br>    <br>    var body: some View {<br>        VStack {<br>            Text(viewModel.userName)<br>            Text(viewModel.email)<br>        }<br>    }<br>}</pre><h4>Conclusion</h4><p>This approach significantly improves the sustainability of the architecture, especially as the number of screens and view models become more complex.</p><p>Although the Dependency Injection Container approach offers significant advantages in terms of scalability and control, it should not be used as the default solution in every project.In small or short-lived applications in particular, this structure can introduce more complexity than benefit. In projects with a few screens and a limited number of dependencies, this level of abstraction can be considered over-engineering.</p><p>Dependency Injection Containers are not a “best practice”; they are a conscious architectural choice. In SwiftUI, they are a powerful solution for clarifying the view lifecycle, controlling the lifespan of dependencies, and ensuring sustainability in medium-to-large scale applications.</p><p>Note: Of course, dependency injection can be done using third-party libraries (Swinject, Factory). The purpose of this article is not to demonstrate how to use third-party libraries, but rather to provide an idea of ​​how this can be solved natively.</p><p>Note: You can find a working example of the patterns described in this article in the <a href="https://github.com/ymnberkay/DI-Demo-iOS"><strong>demo repository</strong></a><strong> .</strong></p><p>You can follow me on <a href="https://www.linkedin.com/in/ymnberkay/"><strong>LinkedIn</strong></a> and <a href="https://github.com/ymnberkay"><strong>Github</strong></a> for more information…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c46dedd88ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>