Instances
One resource opened twice — two Valkeys, two clients of one library — each instance a type of its own, its config and its import named for it.
A provider is found by its type, so one type is one value. When an app needs
two of one resource — a queue’s Valkey, which must never evict, beside a cache’s,
which lives by evicting — each instance is a type of its own: a marker you
declare with #[instance].
use nest_rs::core::instance;
#[instance]pub struct Cache;The marker’s name is its ident in snake case — Cache reads cache, read and
never chosen — and the default instance, Unnamed, is the one an app gets
without naming any.
A module that can be opened once per instance takes the marker as a type
argument where it is imported bare — RedisModule for the default,
RedisModule::<Cache> for the named one — and in the value where its
for_root pins it: x for the default, (Cache, x) for the named one. Its
config then reads <PREFIX>_<VENDOR>__CACHE__* (the vendor first, then the
instance), and its resource is injected as Arc<Resource<Cache>> beside the
default’s Arc<Resource> — Redis is one: RedisModule::<Cache> opens
a second Valkey, injected as
Arc<RedisConnection<Cache>>. Each instance pins its config once; two
instances never contest.
A module generic over the instance is written by hand
(impl<I: Instance> Module for …), since #[module] is not generic:
ForInstance in nest_rs::config shows one whole, and its resource carries the
import a refusal names (CarriesRemedy, on
Providers).
A value your app builds
Section titled “A value your app builds”A value your app builds itself is told apart the same way, by a type. Two
clients of one library are two newtypes — pub struct UpstreamClient(reqwest::Client); — each naming what it reaches. Where the
value must keep its own type, seed it under a marker,
App::builder().provide(Instanced::<Upstream, _>::from(client)), and inject
Arc<Instanced<Upstream, reqwest::Client>>. #[inject] takes no key.
A resource, never a database
Section titled “A resource, never a database”A module takes an instance only for a resource an app opens more than
once, never a database: Repo holds one connection per binary, and a second
database is a second project. An open, extensible set discovered at runtime — a plugin registry,
the social-login providers — is the opposite case: its members are not known
in advance and each carries real code, so it uses the inventory-discovery seam
(a public trait + inventory::submit!); see
social login for the canonical
example.
Going further
Section titled “Going further”- Providers — the container finding each value by its type, and the refusal an unopened instance reads.
- A second Valkey —
RedisModule::<Cache>beside the queue’s server, end to end. - Variables — the namespace an instance’s variables read under.