SunnyDI IoC Container Documentation Status

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