Class: Kanal::Core::Services::ServiceContainer
- Inherits:
-
Object
- Object
- Kanal::Core::Services::ServiceContainer
- 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
-
#get(name) ⇒ Object
Gets the registered service by name.
-
#initialize ⇒ ServiceContainer
constructor
A new instance of ServiceContainer.
-
#register_service(name, service_class, type: TYPE_SINGLETON) { ... } ⇒ void
Registering service so container knows about it and it’s type and it’s optional initialization block.
Methods included from Logging::Logger
Constructor Details
#initialize ⇒ ServiceContainer
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
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
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 |