Meet: Inject, an interesting solution for the DI problem

Hi everyone,

Problem: We want to write code without overhead but be able to replace production instances of the dependencies with the mocks.

I want to propose a solution that allows it with minimum to zero overhead both in performance and a cognitive load for developers, compile time dependency graph validation using swift amazing type system, thread safe using the latest features of swift concurrency:

// GIVEN
protocol MyCoolServiceInterface {}
class MyCoolService: {}

// define the default instance and a name to refer the dependency
extension DefaultValues {
   var myCoolService: MyCoolServiceInterface { MyCoolService() }
}

// USAGE: 
class User {
   @Injected(\myCoolService, lifespan: .permanent, scope: .shared) var service

   func useIt() {
      service.instance.doYou()
   }
}

// Injection example Tests.swift
extension User: Injectable {}

class Test: XCTestCase {
    func test_someUsage() {
      let sut = User().injecting(UserMock(), for: \.service)  
      // now here for sut only the instance of MyCoolServiceInterface is replaced by UserMock
    }
}


// Injection example swfit previews 
struct UserView_Previews: PreviewProvider {
    static var previews: some View {
        UserView()
            .injecting(MockUser(), for: \.service)
    }
}

(It has 100% test coverage, and ,I hope a good, documentation.)
It's also tiny enough to comprehend quicker.

to read more about scopes and lifetimes here's a documentation

I would love to see people interested in trying it out and give me feedback, that I promise to listen to. It can be a small feature, or a greenfield, but real project. I understand that this is a very invasive change so you can start small, and it's interoperable with other solutions.

It's a fundamental library that if you use, usually it means it will be everywhere in the project that's why I don't think I can pull it off by myself, so I'm looking for a contributors as well. not necessarily the code contributions, this is my first public package, so I need help in making it acceptable for a production use.

Thank you for reading till here, I won't spend any more of your time, please let me know if you are interested.

ah yeah, here's the link to the package

5 Likes