예제 #1
0
 def test_simple(self):
     builder = StaticContainerBuilder()
     builder.bind(Interface, Parent)
     builder.bind(DependentInterface, Child)
     builder.bind(CacheInterface, Cache, ScopeEnum.SINGLETON)
     ioc = builder.build()
     parent = ioc.get(Interface)
     cache = ioc.get(CacheInterface)
     parent.method()
     self.assertEqual(cache.get_count(), 1)
예제 #2
0
    def __init__(self, app_name: str, env_key: str = "SERVICE_ENV", **kwargs):

        if "configuration_builder" in kwargs:
            self.__configuration_builder = kwargs["configuration_builder"]
        else:
            self.__configuration_builder = ConfigFactory()

        if "hosting_environment" in kwargs:
            self.__hosting_environment = kwargs["hosting_environment"]
        else:
            self.__hosting_environment = HostingEnvironment(
                application_name=app_name,
                environment_name=os.environ.get(env_key, "Development"))

        self.__settings = dict()
        self.__configDelegates = list()
        self.__serviceDelegates = list()
        self.__configuration = self.__configuration_builder.build()
        self.__services = StaticContainerBuilder()
        self.__services.bind(annotation=ISrvHost, implementation=_NoopHost)
예제 #3
0
파일: const_example.py 프로젝트: en0/pyioc3
from pyioc3 import StaticContainerBuilder

ioc_builder = StaticContainerBuilder()

ioc_builder.bind_constant(annotation="my_constant", value="hello, world")

ioc = ioc_builder.build()

value = ioc.get("my_constant")
print(value)
예제 #4
0
from pyioc3 import StaticContainerBuilder, StaticContainer

ioc_builder = StaticContainerBuilder()


def my_factory_wrapper(ctx: StaticContainer):

    def my_factory(name: str):
        greeting = ctx.get("greeting")
        return "{}, {}!".format(greeting, name)

    return my_factory


ioc_builder.bind_factory(
    annotation="my_factory",
    factory=my_factory_wrapper)
ioc_builder.bind_constant(
    annotation="greeting",
    value="Hello")

ioc = ioc_builder.build()

fact = ioc.get("my_factory")
value: str = fact("Factory")
print(value)
예제 #5
0
def setup_services(ctx, services: StaticContainerBuilder):
    services.bind(ISrvHost, HostMock)
예제 #6
0
class SrvHostBuilder(ISrvHostBuilder):
    __settings: Dict[str, str]
    __configuration: IConfigSection
    __services: StaticContainerBuilder
    __hosting_environment: IHostingEnvironment
    __configuration_builder: IConfigFactory
    __ctx: ISrvHostContext
    __configDelegates: List[ConfigConfigurationDelegate]
    __serviceDelegates: List[ConfigServicesDelegate]

    def __init__(self, app_name: str, env_key: str = "SERVICE_ENV", **kwargs):

        if "configuration_builder" in kwargs:
            self.__configuration_builder = kwargs["configuration_builder"]
        else:
            self.__configuration_builder = ConfigFactory()

        if "hosting_environment" in kwargs:
            self.__hosting_environment = kwargs["hosting_environment"]
        else:
            self.__hosting_environment = HostingEnvironment(
                application_name=app_name,
                environment_name=os.environ.get(env_key, "Development"))

        self.__settings = dict()
        self.__configDelegates = list()
        self.__serviceDelegates = list()
        self.__configuration = self.__configuration_builder.build()
        self.__services = StaticContainerBuilder()
        self.__services.bind(annotation=ISrvHost, implementation=_NoopHost)

    def config_configuration(
            self, config: ConfigConfigurationDelegate) -> ISrvHostBuilder:
        self.__configDelegates.append(config)
        return self

    def config_services(self,
                        config: ConfigServicesDelegate) -> ISrvHostBuilder:
        self.__serviceDelegates.append(config)
        return self

    def add_setting(self, key: str, value: str) -> ISrvHostBuilder:
        self.__settings[key] = value
        return self

    def get_setting(self, key: str):
        if key in self.__settings:
            return self.__settings[key]
        return self.__configuration.get(key)

    def build(self) -> ISrvHost:
        # If custom settings are set, rebuild configuration
        if len(self.__settings) > 0:
            self.__configuration_builder.add_source(
                InMemorySource(config_helpers.explode(self.__settings)))
            self.__configuration = self.__configuration_builder.build()

        # Create a context to start building
        self.__ctx = SrvHostContext(environment=self.__hosting_environment,
                                    configuration=self.__configuration)

        # Call the the configuration delegates
        for configDelegate in self.__configDelegates:
            configDelegate(self.__ctx, self.__configuration_builder)

        # Rebuild configuration after the config delegates have completed
        self.__configuration = self.__configuration_builder.build()
        self.__ctx.configuration = self.__configuration

        # Call the service container delegates
        for serviceDelegate in self.__serviceDelegates:
            serviceDelegate(self.__ctx, self.__services)

        # Add config into the container
        self.__services.bind_constant(annotation=IConfigSection,
                                      value=self.__ctx.configuration)

        # Add environment into the container
        self.__services.bind_constant(annotation=IHostingEnvironment,
                                      value=self.__ctx.environment)

        # Build the service provider
        service_provider = self.__services.build()

        # Get the service host out of the container
        host: ISrvHost = service_provider.get(ISrvHost)

        # Setup the service host
        host.service_provider = service_provider
        host.configuration = self.__ctx.configuration
        host.environment = self.__ctx.environment

        # All done
        return host
예제 #7
0
파일: hacky_example.py 프로젝트: en0/pyioc3
from pyioc3 import StaticContainerBuilder

ioc_builder = StaticContainerBuilder()


def sorta_like_a_factory(name: "name"):

    def but_can_inject_anything():
        print("hello", name(13375))

    return but_can_inject_anything


ioc_builder.bind(
    annotation=5*5*5,
    implementation=sorta_like_a_factory)
ioc_builder.bind_constant(
    annotation="name",
    value=lambda x: "".join([chr(ord(_[0]) ^ ord(_[1])) for _ in zip("Y\x07K\x07G", str(x))]))

ioc = ioc_builder.build()

foo = ioc.get(5**3)
foo()
예제 #8
0
파일: lazy_example.py 프로젝트: en0/pyioc3
from pyioc3 import StaticContainerBuilder


class Squeak:
    def do_quack(self):
        print("SQUEAK")


class RubberDucky:
    def __init__(self, quack_behavior: "squeak"):
        self._quack_behavior = quack_behavior

    def quack(self):
        self._quack_behavior.do_quack()


ioc_builder = StaticContainerBuilder()
ioc_builder.bind(annotation="duck", implementation=RubberDucky)

ioc_builder.bind(annotation="squeak", implementation=Squeak)

ioc = ioc_builder.build()
duck: RubberDucky = ioc.get("duck")

duck.quack()
예제 #9
0
        # Get all subclasses that implement the BASE interface
        for subclass in Base.__subclasses__():

            # Pull each one out of the container and see if it can be used
            inst: Base = ctx.get(subclass)
            if inst.name == name:
                return inst

        # You could also return a default here.
        raise Exception("One of the many issues with the service locator anti-pattern...")

    return create_provider


ioc_builder = StaticContainerBuilder()

# Bind each provider under it's own annotation
ioc_builder.bind(
    annotation=Provider1,
    implementation=Provider1)
ioc_builder.bind(
    annotation=Provider2,
    implementation=Provider2)

# Bind the factory
ioc_builder.bind_factory(
    annotation="create_provider",
    factory=create_provider_factory)

# Application Entry
예제 #10
0
def setup_services(ctx: ISrvHostContext, services: StaticContainerBuilder):
    services.bind(ISrvHost, Host)
    services.bind(Service, Service)
예제 #11
0
파일: basic_example.py 프로젝트: en0/pyioc3

class Duck(metaclass=ABCMeta):
    @abstractmethod
    def quack(self):
        raise NotImplementedError()


class Squeak(QuackBehavior):
    def do_quack(self):
        print("SQUEAK")


class RubberDucky(Duck):
    def __init__(self, squeak: QuackBehavior):
        self._quack_behavior = squeak

    def quack(self):
        self._quack_behavior.do_quack()


ioc_builder = StaticContainerBuilder()
ioc_builder.bind(annotation=Duck, implementation=RubberDucky)

ioc_builder.bind(annotation=QuackBehavior, implementation=Squeak)

ioc = ioc_builder.build()
rubber_duck: Duck = ioc.get(Duck)

rubber_duck.quack()
예제 #12
0
def build_entry(entry_type: EntryInterface, config: IConfigSection) -> EntryInterface:

    ioc_builder = StaticContainerBuilder()

    ioc_builder.bind_constant(
        annotation=IConfigSection,
        value=config)

    ioc_builder.bind_constant(
        annotation=GetChromecastDelegate,
        value=get_chromecasts)

    ioc_builder.bind(
        annotation=CastListenerInterface,
        implementation=CastListener,
        scope=ScopeEnum.TRANSIENT)

    ioc_builder.bind(
        annotation=MessageCreatorInterface,
        implementation=MessageCreator,
        scope=ScopeEnum.TRANSIENT)

    ioc_builder.bind(
        annotation=entry_type,
        implementation=entry_type,
        scope=ScopeEnum.TRANSIENT)

    if config.get("MessageBroker:Type") == "RabbitMQ":
        from gcmon.rabbit_message_broker import RabbitMessageBroker as MessageBroker
    elif config.get("MessageBroker:Type") == "Kafka":
        from gcmon.kafka_message_broker import KafkaMessageBroker as MessageBroker
    else:
        raise RuntimeError("Unsupported message broker.")

    ioc_builder.bind(
        annotation=MessageBrokerInterface,
        implementation=MessageBroker,
        scope=ScopeEnum.TRANSIENT)

    provider = ioc_builder.build()
    return provider.get(entry_type)