This page is also available in Italiano.

Continua in italiano

Container

Container is the only class TinyDI has. An instance owns a set of registrations, keyed by token.

ts
const container = new Container();

registerInstance

Registers an instance you already created. It is always treated as Singleton — every resolve() call returns that exact object.

ts
const ConfigToken = createToken<Config>('Config');
container.registerInstance(ConfigToken, { apiUrl: 'https://example.com' });

registerFactory

Registers a factory used to build the service lazily, on first resolution. The factory receives the container itself, so it can resolve its own dependencies explicitly.

ts
container.registerFactory(
  UserServiceToken,
  (c) => new UserService(c.resolve(UserRepositoryToken)),
);

The third, optional argument is a ServiceLifetime — it defaults to Singleton.

resolve

Resolves the service registered under a token, fully typed with no explicit generic.

ts
const userService = container.resolve(UserServiceToken);

Edge cases

Throws ResolutionError if the token was never registered, and CircularDependencyError if resolving it would require resolving itself again — see the API Reference for the exact error shapes.

has, remove, clear

Manage the registration set directly: has(token) checks whether a token is registered, remove(token) removes a single registration, and clear() removes all of them.

ts
container.has(ConfigToken); // true
 
container.remove(ConfigToken);
container.has(ConfigToken); // false
 
container.clear(); // removes every registration

Replacing a registration

Registering an already-registered token throws RegistrationError, on purpose. Call remove() first — this is deliberately useful for swapping in a fake implementation between tests. See Testing for the full pattern.

to navigate to select Esc to close