Skip to content

Expressing dependencies

Yohan edited this page May 11, 2017 · 3 revisions

Hypodermic will automatically inject the dependencies of your components by passing them to their constructor.

Injecting some instance(s)

class Persister
{
public:
   Persister(const std::shared_ptr< Configuration >& configuration,
             const std::shared_ptr< ISerializer >& serializer);
};

Injecting all instances of a kind

You can get injected all the instances of a particular type like this:

class ConfigManager
{
public:
   ConfigManager(const std::vector< std::shared_ptr< IConfiguration > >& confs);
};

Injecting an instance factory

Sometimes, you will need to be passed a factory that will create your components on demand. That is a way to avoid circular dependencies.

class PipeLoader
{
public:
   explicit PipeLoader(const std::function< std::shared_ptr< IPipe >() >& factory);
};

Under the hood, a lambda with a weak pointer on the container is generated:

[container]() { return container.lock()->resolve< T >(); };

Injecting the container

In some cases, it is convenient to have the container to resolve objects during the lifetime of an application.

template <class THandler>
class HandlerInvoker
{
public:
   explicit HandlerInvoker(const std::shared_ptr< Container >& container);

   void invoke()
   {
      auto container = m_container.lock();
      auto handler = m_container->resolve< THandler >();
   }

private:
   std::weak_ptr< Container > m_container;
};

Note: The container should always be released when your application shuts down so we keep a weak pointer on the container to avoid memory leaks.