Skip to content

Container

Source: shiva-fw/libs/container/init.lua

Service container with dependency injection, singleton support, contracts, and method-level override capabilities. Inspired by Laravel's IoC container.

Availability

Container is a global in every shiva module (loaded by sh_init.lua). No import required.

Registering Services

Container.register(name, implementation)

Register a service by name. Resolves a new instance each time.

lua
Container.register('FishingService', FishingService)

Container.singleton(name, factory)

Register a factory that is called once; the result is cached for all future resolves.

lua
Container.singleton('EconomyService', function()
    return EconomyService.new()
end)

Resolving

Container.resolve(name)

Resolve a registered service by name.

lua
local economy = Container.resolve('EconomyService')

Container.has(name)

Check if a service is registered.

lua
if Container.has('EconomyService') then ... end

Contracts

Container.registerContract(name, contract)

Register a contract (interface) for a service.

lua
Container.registerContract('EconomyService', {
    methods = { 'getBalance', 'addMoney', 'removeMoney' },
    server  = { 'transferMoney' },
})

Container.validateContract(serviceName)

Validate that the registered implementation fulfils its contract. Returns valid and a list of missing method names.

lua
local ok, missing = Container.validateContract('EconomyService')

Container.validateAllContracts()

Validate all registered contracts at once. Returns allValid and a map of serviceName → missing[].

lua
local ok, failures = Container.validateAllContracts()

Overrides (Plugin System)

Container.extend(serviceName, extensions)

Add new methods to an existing service without replacing its core.

lua
Container.extend('EconomyService', {
    logTransaction = function(self, ...) ... end,
})

Container.replace(serviceName, methodName, newFn)

Replace a single method on a registered service. The original is preserved via Container.original().

lua
Container.replace('EconomyService', 'addMoney', function(self, src, amount, reason)
    -- custom logic
    return original(self, src, amount, reason)
end)

Container.original(serviceName, methodName)

Retrieve the original (pre-replace) implementation of a method.

lua
local original = Container.original('EconomyService', 'addMoney')

Utilities

Container.reset()

Unregister all services (used in tests).

Container.getRegistered()

Return a list of all registered service names.

lua
local names = Container.getRegistered()

Released under the MIT License.