Skip to main content

SunnyDI dependency injection framework

Project description

https://img.shields.io/pypi/v/sunnydi.svg https://img.shields.io/pypi/status/sunnydi.svg https://travis-ci.org/thomasstreet/sunnydi.svg?branch=master https://coveralls.io/repos/github/thomasstreet/sunnydi/badge.svg?branch=master 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):
        self.bind('hello_service')
            .to(HelloService)

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()
'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()
'hello'

For advanced usage, checkout the docs

Project details


Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page