Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Service @injection does not seem to work in latest sanic 24.6 #818

Open
linuxd3v opened this issue Sep 12, 2024 · 0 comments
Open

Service @injection does not seem to work in latest sanic 24.6 #818

linuxd3v opened this issue Sep 12, 2024 · 0 comments

Comments

@linuxd3v
Copy link

linuxd3v commented Sep 12, 2024

Trying to inject a service from declarative container into sanic handler - but service never get's injected.

container example:

class AppContainer(containers.DeclarativeContainer):
    # https://python-dependency-injector.ets-labs.org/providers/inject_self.html
    __self__ = providers.Self()

    # This will wire automatically   - once you instantiate the container
    wiring_config = containers.WiringConfiguration(
        packages=[
            "xasperuze.routers",
        ],
    )

    # Add your container initialization code below
    # ========================================================================

    # Application config
    appconfig: providers.Configuration = providers.Configuration()

    # jinja service
    svc_templater: Singleton[Environment] = providers.Singleton(
        Jinjia2Factory().get_svc,
        app_path=appconfig.app_path,
        THEME_REL_PATH=appconfig.THEME_REL_PATH,
        SITE_THEME_NAME=appconfig.SITE_THEME_NAME,
        ENV_NAME=appconfig.ENV_NAME,
        # Injecting the vite loader service as a provider, so we only resolve it when needed.
        # Otherwise "providers.Self()" wont be available
        svc_vite_loader=svc_vite_loader.provider,
        utils=utils,
    )

Injecting service into route in sanic:

from dependency_injector.wiring import Provide, inject

bp = Blueprint("my_page3")

def get_blueprint() -> Blueprint:
    @bp.route("/test/route<path:path>", methods=["GET"])
    @inject
    async def handler_rd(
        request,
        path: str,
        svc_templater: Environment = Provide[AppContainer.svc_templater],
    ):
        #This doesnt work
        templater_injected = svc_templater

        #This works
        templater_from_ctx: Environment = request.ctx.container.svc_templater()

        return text(f"RD - {path}")

I can pull my service from a container I share via sanic context (ex: templater_from_ctx), but the one I try to inject via Provide[AppContainer.svc_templater] - always comes back as Provider object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant