Skip to content

Custom providers

We will learn to have same way how NestJs create and use providers.

Standard providers

Python
@Module(
    controllers=[CatsController],
    providers=[CatsService],
)

Value providers

Python
from nestipy.common import ModuleProviderDict


@Module(
    controllers=[CatsController],
    providers=[
        ModuleProviderDict(
            token=CatsService,
            value=CatsService
        )
    ],
)

Non-class-based provider tokens

Python
from nestipy.common import Module, ModuleProviderDict
from .connection import connection


@Module(
    controllers=[CatsController],
    providers=[
        ModuleProviderDict(
            token='CONNECTION',
            value=connection
        )
    ],
)
class AppModule:
    pass

For, use_class and use_existing, it's the same as NestJs.

Factory provider

Python
from nestipy.common import ModuleProviderDict, Module
from .connection import connection


def factory_value() -> str:
    return connection


@Module(
    controllers=[CatsController],
    providers=[
        ModuleProviderDict(
            token='CONNECTION',
            factory=factory_value
        )
    ],
)
class AppModule:
    pass

Factory can be an async function to have async provider.

Inject providers

Python
from typing import Annotated
from nestipy.common.decorator import Controller
from nestipy.ioc import Inject


@Controller('cats')
class CatsController:
    connection: Annotated[str,Inject('CONNECTION')]
    cat_service: Annotated[CatsService, Inject()]

Exporting non-class based provider works perfectly.

Support us

Nestipy is a project released under the MIT license, meaning it's open source and freely available for use and modification. Its development thrives with the generous contributions of these fantastic individuals.