Created
August 8, 2013 15:57
-
-
Save alecthomas/6185882 to your computer and use it in GitHub Desktop.
Example of using Injector without annotating application-level classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from injector import Module, Injector, provides, inject, singleton | |
from some_credit_card_provider import CreditCardConnection, CreditCardVendor | |
class CreditCardProcessor(object): | |
def __init__(self, vendor, connection): | |
self.vendor = vendor | |
self.connection = connection | |
def charge_order(self, card, amount): | |
self.connection.charge_order(self.vendor, card, amount) | |
class TransactionLog(object): | |
def __init__(self): | |
self.log = [] | |
def log_order(self, user, amount): | |
self.log.append((user, amount)) | |
class BillingService(object): | |
def __init__(self, credit_card_processor, transaction_log): | |
self.credit_card_processor = credit_card_processor | |
self.transaction_log = transaction_log | |
def charge_order(self, order, credit_card): | |
self.credit_card_processor.charge_order() | |
class Cart(object): | |
def __init__(self, billing_service): | |
self.billing_service = billing_service | |
self.order = [] | |
def add(self, item): | |
self.order.append(item) | |
def checkout(self, credit_card): | |
self.billing_service.charge_order(self.order, credit_card) | |
class ShoppingModule(Module): | |
def __init__(self, vendor_id): | |
self.vendor_id = vendor_id | |
@provides(BillingService, scope=singleton) | |
@inject(credit_card_processor=CreditCardProcessor, transaction_log=TransactionLog) | |
def provide_billing_service(self, credit_card_processor, transaction_log): | |
return BillingService(credit_card_processor, transaction_log) | |
@provides(CreditCardProcessor, scope=singleton) | |
@inject(vendor=CreditCardVendor, connection=CreditCardConnection) | |
def provide_credit_card_processor(self, vendor, connection): | |
return CreditCardProcessor(vendor, connection) | |
@provides(CreditCardConnection, scope=singleton) | |
def provide_credit_card_connection(self): | |
return CreditCardConnection() | |
@provides(CreditCardVendor, scope=singleton) | |
def provide_vendor(self): | |
return CreditCardVendor(self.vendor_id) | |
@provides(Cart) | |
@inject(billing_service=BillingService) | |
def provide_cart(self, billing_service): | |
return Cart(billing_service) | |
def main(): | |
injector = Injector([ShoppingModule('my_vendor_id')]) | |
cart = injector.get(Cart) | |
cart.add('some item') | |
cart.add('some other item') | |
cart.checkout('xxxx xxxx xxxx xxxx') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment