useValue
Using useValue
in Providers
The useValue
option allows you to register a fixed value or object as a dependency in the container. This is particularly useful for static configurations, constants, or objects that don’t need to be instantiated.
Example: Registering a Configuration Object
Suppose you have a configuration object for your application:
const AppConfig = {
appName: "Depinjionary",
version: "1.0.0",
debug: true
};
You can register it as a provider using useValue
:
import { ContainerResolver } from "depinjionary";
const providers = [
{ provide: "AppConfig", useValue: AppConfig }
];
const container = ContainerResolver.init(providers);
const config = await container.resolve<{ appName: string, debug: boolean }>("AppConfig");
console.log(config.appName); // Outputs: "Depinjionary"
console.log(config.debug); // Outputs: true
Example: Using useValue
for Constants
If you need to register a simple constant, useValue
is also a great choice:
const API_ENDPOINT = "https://api.example.com";
const providers = [
{ provide: "ApiEndpoint", useValue: API_ENDPOINT }
];
const container = ContainerResolver.init(providers);
const endpoint = await container.resolve<string>("ApiEndpoint");
console.log(endpoint); // Outputs: "https://api.example.com"
Key Notes
-
When to Use
useValue
:- For static data like configurations, constants, or shared objects.
- When no instantiation logic is required.
-
Accessing Values:
- Use the
provide
key as the token to retrieve the value from the container.
- Use the
-
Best Practices:
- Use descriptive tokens (e.g.,
"AppConfig"
,"ApiEndpoint"
) to avoid confusion. - Combine with other types of providers (
useClass
,useFactory
) for a well-structured dependency setup.
- Use descriptive tokens (e.g.,