Class: Kanal::Core::Services::ServiceContainer

Inherits:
Object
  • Object
show all
Includes:
Logging::Logger
Defined in:
lib/kanal/core/services/service_container.rb

Overview

Container allows service registration as well as getting those services. You can register service with different lifespan types.

Constant Summary collapse

TYPE_SINGLETON =
:singleton
TYPE_TRANSIENT =
:transient

Instance Method Summary collapse

Methods included from Logging::Logger

#logger

Constructor Details

#initializeServiceContainer

Returns a new instance of ServiceContainer.



36
37
38
39
# File 'lib/kanal/core/services/service_container.rb', line 36

def initialize
  @registrations = {}
  @services = {}
end

Instance Method Details

#get(name) ⇒ Object

Gets the registered service by name

Parameters:

  • name (Symbol)

    <description>

Returns:

  • (Object)

    <description>



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/kanal/core/services/service_container.rb', line 82

def get(name)
  raise "Service named #{name} was not registered in container" unless @registrations.key? name

  registration = @registrations[name]

  case registration.type
  when TYPE_SINGLETON
    # Created once and reused after creation
    @services[name] = create_service_from_registration registration if @services[name].nil?

    @services[name]
  when TYPE_TRANSIENT
    # Created every time
    create_service_from_registration registration
  end
end

#register_service(name, service_class, type: TYPE_SINGLETON) { ... } ⇒ void

This method returns an undefined value.

Registering service so container knows about it and it’s type and it’s optional initialization block

Parameters:

  • name (Symbol)

    <description>

  • service_class (class)

    <description>

  • type (Symbol) (defaults to: TYPE_SINGLETON)

    <description>

Yields:

  • Initialization block. It should be used if your service requires postponed initialization



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/kanal/core/services/service_container.rb', line 53

def register_service(name, service_class, type: TYPE_SINGLETON, &block)
  logger.info "Trying to register service '#{name}'"

  if @registrations.key? name
    logger.warn "Attempted to register service '#{name}', but it is already registered"

    return
  end

  unless allowed_types.include? type
    logger.fatal "Attempted to register service type '#{type}'."

    raise "Unrecognized service type #{type}. Allowed types: #{allowed_types}"
  end

  registration = ServiceRegistration.new service_class, type, block

  logger.info "Registering service '#{name}'"

  @registrations[name] = registration
end