Skip to main content

MakeWithDependencies

Make a new instance of a class and provide it the dependencies handler as first constructor parameter.

template <typename T, typename... Args>
T MakeWithDependencies(Args&&... args);

This method takes a template parameter T which is the class to instantiate.

Parameters​

  • T: The class to instantiate.
  • args: The arguments to pass to the class constructor.

Return value​

  • An instance of the class T.

Notes​

info

If you want to get access to the current DependenciesHandler instance in the constructor of the service, you can pass a DependenciesHandler::Ptr as the first argument of the constructor.

Examples​

class MyService {
public:
MyService() = default;
~MyService() = default;

int GetNextValue() { return counter_++; }

private:
int counter_ = 0;
};

class MyClass {
public:
explicit MyClass(DependenciesHandler::Ptr handler) : handler_(handler) {}

void Display() {
auto service = handler_->Get<MyService>();

std::cout << service.GetNextValue() << std::endl;
}

private:
DependenciesHandler::Ptr handler_;
};

class MyClassWithNoDeps {
public:
MyClassWithNoDeps() = default;

void Display() { std::cout << "Hello, world!" << std::endl; }
};

int main() {
auto handler = DependenciesHandler::Create();

handler->Add<MyService>();

auto myClass = handler->MakeWithDependencies<MyClass>();
auto myClassWithNoDeps = handler->MakeWithDependencies<MyClassWithNoDeps>();

myClass.Display(); // Will print 0
myClass.Display(); // Will print 1
myClass.Display(); // Will print 2
myClassWithNoDeps.Display(); // Will print "Hello, world!"

return 0;
}