Dependency Injection in C ++

How to implement explicit dependency injection in C ++ explicitly without using frameworks or reflections?

I could use factory to return auto_ptr or shared_ptr. Is this a good way to do this?

+4
source share
3 answers

Just use shared_ptr for the service you need and create a setter for it. For instance:.

class Engine; class Car { public: void setEngine(shared_ptr<Engine> p_engine) { this->m_engine = p_engine; } int onAcceleratorPedalStep(int p_gas_pedal_pressure) { this->m_engine->setFuelValveIntake(p_gas_pedal_pressure); int torque = this->m_engine->getTorque(); int speed = ... //math to get the car speed from the engine torque return speed; } protected: shared_ptr<Engine> m_engine; } // (now must create an engine and use setEngine when constructing a Car on a factory) 

Avoid using auto_ptr because you cannot share it across multiple objects (it transfers ownership when assigned).

+4
source

AFAIK dependency injection simply means that there is an interface to a component that is required by another.

 namespace ifc { struct service { virtual ~service() {} virtual do_stuff(/*..*/) = 0; }; } // ns ifc class ServiceProviderA : public ifc::service { public; do_stuff(/*..*/) { /*...*/ } }; class ServiceProviderB : public ifc::service {/*...*/}; class Client { public; client(ifc::service*); private: ifc::service* m_service; }; 

I can only guess, but this is your question, how to manage the lifetime of an embedded object?

+1
source

How about the ownership of the transferred object being transferred to the dependent object. This will solve the problem of life expectancy for the composition, avoiding the use of smart pointers. But for difficult situations, when owning important smart pointers will be a choice.

 class Car { public: Car(IEngine *pEngine) { m_pEngine = pEngine; } ... ~Car() { delete m_engine; } protected: IEngine *m_pEngine; } 

In cases where the dependency undoubtedly has a shorter lifetime than the injected object, it is better to pass the embedded object as a reference. This will clearly indicate that the injected object does not belong to the dependent object.

0
source

All Articles