Skip to main content

modern-di-grpc

PyPI version Supported Python versions Downloads Coverage CI License GitHub stars uv Ruff ty

Modern-DI integration for gRPC (grpcio).

Full guide: gRPC integration docs

Usage example: examples/

Installation

uv add modern-di-grpc      # or: pip install modern-di-grpc

Usage

gRPC has no dependency-injection system of its own, so modern-di-grpc pairs an @inject decorator with inert FromDI markers. A DIInterceptor (sync) or DIAioInterceptor (async) opens one Scope.REQUEST child container per RPC and resolves the FromDI-marked parameters of @inject-decorated servicer methods. Constructing the interceptor registers the ServicerContext provider on the container automatically — there is no separate setup call.

import typing
from concurrent import futures

import grpc
from modern_di import Container, Group, Scope, providers
from modern_di_grpc import DIInterceptor, FromDI, inject

from myapp import greeter_pb2, greeter_pb2_grpc  # your generated stubs


class Settings:
    def __init__(self) -> None:
        self.greeting = "hello"


class Greeter:
    def __init__(self, settings: Settings) -> None:  # auto-injected by type
        self._settings = settings

    def greet(self, name: str) -> str:
        return f"{self._settings.greeting}, {name}"


class AppGroup(Group):
    settings = providers.Factory(Settings, scope=Scope.APP, cache=True)
    greeter = providers.Factory(Greeter, scope=Scope.REQUEST)


class GreeterService(greeter_pb2_grpc.GreeterServicer):
    @inject
    def SayHello(
        self,
        request: greeter_pb2.HelloRequest,
        context: grpc.ServicerContext,
        greeter: typing.Annotated[Greeter, FromDI(Greeter)],  # resolve by type
    ) -> greeter_pb2.HelloReply:
        return greeter_pb2.HelloReply(message=greeter.greet(request.name))


container = Container(groups=[AppGroup])
container.validate()  # optional fail-fast; modern-di 3.1 validates nowhere implicitly
server = grpc.server(
    futures.ThreadPoolExecutor(max_workers=10),
    interceptors=[DIInterceptor(container)],
)
greeter_pb2_grpc.add_GreeterServicer_to_server(GreeterService(), server)
server.add_insecure_port("[::]:50051")
server.start()
server.wait_for_termination()
container.close_sync()

For an async server, pass DIAioInterceptor(container) to grpc.aio.server(...) and write async def servicer methods; @inject adapts to sync, async, and async-generator (server-streaming) methods across all four RPC types. gRPC has no server startup/shutdown hook, so the root container's shutdown is yours to own. As of modern-di 3.1 a container is open from construction, so no .open() call is required before constructing the interceptor (DIInterceptor/DIAioInterceptor never open the root themselves, and no longer need to). Validation is explicit in 3.1: call .validate() if you want a broken graph to fail at start-up rather than at the first RPC that touches it. Call close_sync() (or await close_async() on grpc.aio) after the server stops — that half is still yours, since gRPC gives the adapter no shutdown hook.

API

Symbol Description
DIInterceptor(container) grpc.ServerInterceptor for the sync thread-pool server. Opens a Scope.REQUEST child per RPC (close_sync); auto-registers grpc_context_provider
DIAioInterceptor(container) grpc.aio.ServerInterceptor for the async server. Same, with close_async
FromDI(dependency) Inert marker for Annotated[T, FromDI(...)] in servicer-method signatures; accepts a provider instance or a type
inject(method) Decorates a servicer method to resolve its FromDI parameters from the current RPC's child container; adapts to sync / async / async-generator methods
fetch_di_container() Returns the current RPC's child container (raises LookupError outside an RPC)
grpc_context_provider ContextProvider exposing grpc.ServicerContext at Scope.REQUEST; auto-registered by the interceptor

📦 PyPI

📝 License

Part of modern-python

Built on modern-di, a dependency-injection framework with IoC container and scopes.

Browse the full list of templates and libraries in modern-python — see the org profile for the categorized index.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

modern_di_grpc-3.0.1.tar.gz (5.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

modern_di_grpc-3.0.1-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

Details for the file modern_di_grpc-3.0.1.tar.gz.

File metadata

  • Download URL: modern_di_grpc-3.0.1.tar.gz
  • Upload date:
  • Size: 5.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.33 {"installer":{"name":"uv","version":"0.11.33","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for modern_di_grpc-3.0.1.tar.gz
Algorithm Hash digest
SHA256 3e1b0602fb1de774f7d7b0f6128ea20d21c5a06ba48af656641003893d14f54b
MD5 47911f7e0b2bb82aa3c708ddfd4d3a09
BLAKE2b-256 d7b9ccff25fa60d7ca846842bb2d8f7c63cd99a21b65c4fa404010bdecd7e323

See more details on using hashes here.

File details

Details for the file modern_di_grpc-3.0.1-py3-none-any.whl.

File metadata

  • Download URL: modern_di_grpc-3.0.1-py3-none-any.whl
  • Upload date:
  • Size: 6.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.33 {"installer":{"name":"uv","version":"0.11.33","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for modern_di_grpc-3.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 6842bc1c52bc8cdb949c9106bcb415f6d0c5a29be06687a6700441f279c25596
MD5 599bb63885e5e73415f171f2785b44de
BLAKE2b-256 07f6b73c6e79d650f22b913366d9d7f71d63736114afb0ad7a41eda4ce8298c2

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

3.0.1 This release

2 files

3.0.0

2 files

2.1.0

2 files

2.0.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page