Container

public protocol Container: BasicWorker

Containers are used to create instances of services that your application needs in a configurable way.

let client = try container.make(Client.self)

Each Container has Config, Environment, and Services. It uses this information to dynamically provide services based on your configuration and environment.

switch env {
case .production: config.prefer(ProductionLogger.self, for: Logger.self)
default: config.prefer(DebugLogger.self, for: Logger.self)
}

...

let logger = try container.make(Logger.self) // changes based on environment

Containers are also Workers, meaning they have a reference to an EventLoop.

print(container.eventLoop)

Warning

You should never use services created from a Container on another Container’s EventLoop.
  • make(_:) Extension method

    Creates a service for the supplied interface or type.

    let redis = try container.make(RedisCache.self)
    

    If a protocol is supplied, a service conforming to the protocol will be returned.

    let client = try container.make(Client.self)
    print(type(of: client)) // EngineClient
    

    Subsequent calls to make(_:) for the same type will yield a cached result.

    Throws

    Any error finding or initializing the requested service.

    Declaration

    Swift

    public func make<T>(_ type: T.Type = T.self) throws -> T

    Parameters

    type

    Service or interface type T to create.

    Return Value

    Initialized instance of T

  • subContainer(on:) Extension method

    Creates a SubContainer for this Container on the supplied Worker.

    Declaration

    Swift

    public func subContainer(on worker: Worker) -> SubContainer

    Parameters

    worker

    Worker containing a different EventLoop for the SubContainer to use.

    Return Value

    Generic instance of a SubContainer.

  • providers Extension method

    All Providers that have been registered to this Container’s Services.

    Declaration

    Swift

    public var providers: [Provider]