💉 sinj
sinj
(Simple Inject) is yet another IoC framework for python. If you try to avoid global variables and singletons you might end up with a complex graph of dependencies in your application. With sinj
everything is just flat. If you are coming from Java or C# you might be more familiar with IoC frameworks where dependencies are resolved by interface. In python we do not have interfaces and strict types so here we resolve dependencies by constructor argument names or "inject labels".
Basic usage and examples
import sinj
c = sinj.Container()
c.register(SomeClass, "some_class")
c.resolve("some_class")
c.inject(some_instance, "some_instance")
The simplest example:
import sinj
class A:
def a(self):
return "a"
class B:
def __init__(self, a):
self._a = a
def b(self):
return self._a() + " b"
ioc_container = sinj.Container()
ioc_container.register(A, "a")
ioc_container.register(B, "b")
b = ioc_container.resolve("b")
print(b.b())
The same example with annotated classes:
import sinj
class A:
inject = "a"
def a(self):
return "a"
class B:
inject = "b"
def __init__(self, a):
self._a = a
def b(self):
return self._a() + " b"
ioc_container = sinj.Container()
ioc_container.register(A)
ioc_container.register(B)
b = ioc_container.resolve("b")
print(b.b())
More examples will be available in ./examples
Errors
sinj.DependencyNotFoundError
- thrown on resolve
when dependency is not found for a given label (and it is not optional).
sinj.CircularDependencyError
- thrown on resolve
when circular dependency is detected.
sinj.DependencyConflictError
- thrown on register
or inject
when the container already has something by the label.
sinj.DependencyNotMappedError
- thrown on register
or inject
when the class is not annotated and the label is not provided in register method.
Install
pip install sinj
pip install git+https://gitlab.com/mrsk/sinj