service_collection
service_collection
is a lightweight Python package that mimics ASP.NET's dependency injection system. It also incorporates an Angular-style Inject
method to resolve dependencies, making it easier to manage and inject dependencies in your applications.
It currently supports transient and singleton services. Scoped services will be added in a future release if there is a demand for them.
Installation
Install the package using pip:
pip install service-collection
Usage
Setting Up the Service Collection
- Define your services and interfaces:
from abc import ABC, abstractmethod
from service_collection import inject
class IFooService(ABC):
@abstractmethod
def do_something(self):
pass
class FooService(IFooService):
def do_something(self):
return "FooService did something!"
class IBarService(ABC):
@abstractmethod
def do_something(self):
pass
class BarService(IBarService):
def __init__(self):
self.foo_service = inject(IFooService)
def do_something(self):
return f"BarService did something with {self.foo_service.do_something()}"
- Register your services:
from service_collection import ServiceCollection
services = ServiceCollection()
services.add_transient(IFooService, FooService)
services.add_singleton(IBarService, BarService)
- Build the service provider:
service_provider = services.build_service_provider()
Creating and Using the Inject Function
Import the inject
function to retrieve service instances easily in your code:
from service_collection import inject
foo_service = inject(IFooService)
print(foo_service.do_something())
bar_service = inject(IBarService)
print(bar_service.do_something())
Full Example
Here is a complete example demonstrating how to set up and use the service_collection
package with the inject
function:
from abc import ABC, abstractmethod
from service_collection import ServiceCollection, inject
class IFooService(ABC):
@abstractmethod
def do_something(self):
pass
class FooService(IFooService):
def do_something(self):
return "FooService did something!"
class IBarService(ABC):
@abstractmethod
def do_something(self):
pass
class BarService(IBarService):
def __init__(self):
self.foo_service = inject(IFooService)
def do_something(self):
return f"BarService did something with {self.foo_service.do_something()}"
services = ServiceCollection()
services.add_transient(IFooService, FooService)
services.add_singleton(IBarService, BarService)
service_provider = services.build_service_provider()
foo_service = inject(IFooService)
print(foo_service.do_something())
bar_service = inject(IBarService)
print(bar_service.do_something())
License
This project is licensed under the MIT License. See the LICENSE file for details.
This README provides an overview of how to install, set up, and use the service_collection
package with example code snippets, demonstrating the use of abstract base classes for service interfaces and including the creation and usage of the inject
function.