hmlongco / Factory

A new approach to Container-Based Dependency Injection for Swift and SwiftUI.
MIT License
1.93k stars 116 forks source link

Use rethrowing factory registration #198

Closed MrSkwiggs closed 8 months ago

MrSkwiggs commented 8 months ago

I find myself stuck because some of my factory's are throwing, and I don't want to do error handling in the container

MrSkwiggs commented 8 months ago

Hmmm this actually requires a lot more work than anticipated, but I do see the value in perhaps vending a ThrowingFactory & ThrowingParameterFactory @hmlongco what do you think? If you agree I'll implement these in here

hmlongco commented 8 months ago

Yeah, that would be a set of pervasive changes to everything. Might should just try something like...

struct Throwing<T> {
    private let factory: () throws -> T
    init(_ factory: @escaping () throws -> T) {
        self.factory = factory
    }
    func callAsFunction() throws -> T {
        try factory()
    }
}

class Dummy {
    init() throws {
        throw CancellationError() // just an error
    }
}

extension Container {
    var throwingDummyFactory: Factory<Throwing<Dummy>> {
        self {
            .init { try Dummy() }
        }
    }
    func test() {
        let dummy: Dummy? = try? throwingDummyFactory()()
    }
}

Not pretty, but at least a partial solution.

MrSkwiggs commented 8 months ago

@hmlongco Yeah that, or just:

extension Container {
  typealias ThrowingFunc = () throws -> Void

  var myThrowingFactory: Factory<ThrowingFunc> {
    self {{ try someCodeThatThrows() }}
  }

  func test() {
    // do something dangerous
    try? myThrowingFactory()()
  }
}

But the ()() really irks me ðŸ«