Lua IOC (Dependency Injection Library)

Lua IOC (Dependency Injection Library)

Description

I know not many devs in FiveM will make an use of this library, as the majority of the people just do scripting and OOP is not really needed.

However, for those who want to emulate some kind of OOP in LUA, either with metatables or any other approach, they will most likely need some kind of Dependency Injection.

This library is just a DI library to perform IOC in your application (inversion of control)
It is really opinionated, and do not support autowiring.

I used it during the 2/3 years I’ve been scripting in FiveM and now I want to share it with others just in case it helps.

Features

  • Register Classes/Functions into a container.
  • Provides a way to define factories into the container.
  • Retrieve a intitialized class from a container.

Link to repository

Getting started

The library can be used by reference or as a dependency with exports.

I decided to not expose default container implementation, and delegate it to the developer consuming the library. Its up to you where to create a container or not.

Anyway creating a container is really simple. For more detailed documentation go into the repository readme.

By reference

If you have your application in a single script or into a Framework like ESX/QB, you can reference
the scripts and instantiate the ContainerBuilder in your application.

Also you can create a script only responsible of creating this Containers and exporting them in some way.
Or add this logic in the script itself, thats on you and how far you want to go with the SRP.

client_scripts {
    ...,
    '@fivem-ioc/src/ContainerBuilder.lua',
    '@fivem-ioc/src/Definition.lua',
    '@fivem-ioc/src/InstanceManager.lua',
    ...,
}

server_scripts {
    ...,
    '@fivem-ioc/src/ContainerBuilder.lua',
    '@fivem-ioc/src/Definition.lua',
    '@fivem-ioc/src/InstanceManager.lua',
    ...,
}

As dependency with exports

I never used this approach to be honest, but it is there. The manifest exposes exports for both ContainerBuilder and Definition objects. You can import them in your scripts.

Basic Usage

ClientContainer = ContainerBuilder()
ClientContainer:register('DummyService', DummyService)
ClientContainer:register('DummyModule', Dummy):addArgument('Reference', 'DummyService')

my_module = ClientContainer:get('DummyModule')
my_module:do_stuff()
1 Like