Registering Services
Services are registered with AppBuilder before the application is built.
For a singleton service with no dependencies:
mach::AppBuilder builder;
builder.addSingleton<UserService>();
auto app = builder.build();Once registered, UserService can be resolved as a dependency of other services and framework components.
Register Service Dependencies
Section titled “Register Service Dependencies”If a service has constructor dependencies, list them as additional template arguments when registering it.
For example:
class UserRepository {public: // ...};
class UserService {public: explicit UserService(UserRepository& repository) : m_repository(repository) {}
private: UserRepository& m_repository;};Register both services and declare the dependency:
mach::AppBuilder builder;
builder.addSingleton<UserRepository>();builder.addSingleton<UserService, UserRepository>();
auto app = builder.build();UserService declares UserRepository as a dependency, so Mach resolves the repository and passes it to the UserService constructor.
Multiple Dependencies
Section titled “Multiple Dependencies”A service can depend on multiple other services:
class UserService {public: UserService(UserRepository& repository, AuditService& auditService) : m_repository(repository), m_auditService(auditService) {}
private: UserRepository& m_repository; AuditService& m_auditService;};Declare each dependency when registering the service:
builder.addSingleton<UserService, UserRepository, AuditService>();The dependency template arguments must match the constructor parameters in the same order.
Registration Order
Section titled “Registration Order”Services do not need to be registered in dependency order.
For example, this is valid:
mach::AppBuilder builder;
builder.addSingleton<UserService, UserRepository>();builder.addSingleton<UserRepository>();
auto app = builder.build();Even though UserService is registered first, Mach can resolve its dependency once the application is built because UserRepository has also been registered.
What matters is that all required services are registered before build().
Register Before Building
Section titled “Register Before Building”Service registration is part of application configuration and must happen before the application is built:
mach::AppBuilder builder;
builder.addSingleton<UserRepository>();builder.addSingleton<UserService, UserRepository>();
auto app = builder.build();At build time, Mach has the service registrations it needs to construct and resolve the application’s dependency graph.
Next, you’ll learn how service lifetimes determine when service instances are created and reused.