Created
February 18, 2016 13:04
-
-
Save pgk/b9135fb1cd3bb6063a1e to your computer and use it in GitHub Desktop.
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
mport inspect | |
class Container(object): | |
def __init__(self): | |
self.registry = {} | |
def register(self, interface, implementation): | |
self.registry[interface.__name__] = implementation | |
def resolve(self, entity): | |
if entity.__name__ in self.registry: | |
creator = self.registry[entity.__name__] | |
else: | |
creator = entity | |
init_func = creator.__init__ | |
arg_spec = inspect.getfullargspec(init_func) | |
arg = arg_spec.args.copy() | |
arg.remove('self') | |
if len(arg) == 0: | |
return entity() | |
if len(arg) != len(arg_spec.annotations): | |
raise ValueError('missing annotations for arguments') | |
init_args = {} | |
for argname, interface in arg_spec.annotations.items(): | |
if interface.__name__ in self.registry: | |
implementation = self.registry[interface.__name__] | |
impl_instance = self.resolve(implementation) | |
init_args[argname] = impl_instance | |
return entity(**init_args) | |
if __name__ == '__main__': | |
class ICallable(object): | |
pass | |
class ConcreteCallable(object): | |
def call(self): | |
return 1 | |
class Consumer(object): | |
def __init__(self, c: ICallable): | |
self.c = c | |
container = Container() | |
container.register(ICallable, ConcreteCallable) | |
cc = container.resolve(ConcreteCallable) | |
print(cc.call()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment