Skip to content

iballan/BasicServiceLocator

Repository files navigation

BasicServiceLocator

Very BasicServiceLocator for Swift

Installation

CocoaPods

pod 'BasicServiceLocator'

Swift Package Manager

Once you have your Swift package set up, adding SwiftyTimber as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/iballan/BasicServiceLocator.git", .upToNextMajor(from: "0.0.4"))
]

USAGE

// Protocols
protocol ServiceA {}
protocol ServiceB {}

// Implementation
class ServiceAA: ServiceA {}
class ServiceBB: ServiceB {}

// Fake or Debug Implementation
class FakeServiceB: ServiceB{}

// Service Resolver and Container
let serviceLocator : ServiceLocator = BasicServiceLocator()

// Registering
serviceLocator.registerService(ServiceA.self, instance: ServiceAA())
serviceLocator.registerService(ServiceB.self) {
    #if DEBUG
        return FakeServiceB()
    #else
        return ServiceBB()
    #endif
}

// Fetching and using service
let serviceA = try? serviceLocator.getService(ServiceA.self)
let serviceB = try! serviceLocator.getService(ServiceB.self)

Transient (Non-Singleton) Services

You can register services that produce a new instance on every lookup using registerTransientService. This is useful for per-screen or per-request scopes:

// Define a transient service protocol and implementation
protocol ScreenScopeService {}
class ScreenScopeServiceImpl: ScreenScopeService {}

// Register as transient (new instance each time)
serviceLocator.registerTransientService(ScreenScopeService.self) {
    return ScreenScopeServiceImpl()
}

// Every getService call returns a fresh instance
let firstInstance = try serviceLocator.getService(ScreenScopeService.self)
let secondInstance = try serviceLocator.getService(ScreenScopeService.self)
assert(firstInstance !== secondInstance) // they are different objects

About

Very BasicServiceLocator for Swift

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors