Skip to main content
This is a pre-production deployment of Warehouse. Changes made here affect the production instance of PyPI (
Help us improve Python packaging - Donate today!

SunnyDI dependency injection framework

Project Description

SunnyDI is an IoC container for managing and injecting dependencies in Python.

It is inspired by Autofac for .NET and Guice for java.

How to Use

For our example, we will create an IoC module for our HelloService.:

class HelloService(object):
    def hello(self):
        return 'hello'

Create a new configuration module that extends sunnydi.ioc.Module. A module defines how objects will be created, destroyed and provided to other object instances in the IoC object graph. In the most simple configuration, we can just bind a string name to our HelloService class type:

class HelloModule(Module):
    def configure(self):

We can then create the injector and resolve our HelloService like this:

>>> hello_module = HelloModule()
>>> injector = hello_module.create_injector()
>>> hello_service = injector.get('hello_service')

>>> hello_service.hello()

Resolved instances are provided via constructor arguments to consuming classes. For instance, given the following class:

class MyClass(object):

    def __init__(self, hello_service):
        self._hello_service = hello_service

    def do_hello(self):
        return self._hello_service.hello()

An instance of MyClass can be resolved with an instance of HelloService due to the service’s binding name matching the parameter defined in the MyClass constructor:

>>> my_class_instance = injector.get(MyClass)
>>> my_class_instance.do_hello()

For advanced usage, checkout the docs

Release History

This version
History Node


Supported By

WebFaction WebFaction Technical Writing Elastic Elastic Search Pingdom Pingdom Monitoring Dyn Dyn DNS Sentry Sentry Error Logging CloudAMQP CloudAMQP RabbitMQ Heroku Heroku PaaS Kabu Creative Kabu Creative UX & Design Fastly Fastly CDN DigiCert DigiCert EV Certificate Rackspace Rackspace Cloud Servers DreamHost DreamHost Log Hosting