pub struct HostBuilder { /* private fields */ }Implementations§
Source§impl HostBuilder
impl HostBuilder
pub fn new() -> Self
pub fn register<F>(self, f: F) -> Self
pub fn configure<F>(self, f: F) -> Self
pub fn mode(self, mode: AppMode) -> Self
Sourcepub fn lenient_scope_validation(self) -> Self
pub fn lenient_scope_validation(self) -> Self
Keep the pre-1.0 (rust-dix 0.7) lenient root-scope behavior.
1.0 defaults to strict scope validation (MEDI ValidateScopes = true):
resolving a Scoped service from the root ServiceProvider returns
webx::Error::Di instead of silently caching it on the
root. Existing code that resolves Scoped services from
host.provider() can opt back in here while it migrates to explicit
scopes (provider.scope() / get_owned) — see
docs/rust-webx/16-migration/upgrade-to-1.0.md.
Sourcepub fn add_options<T>(self, section: &str) -> Self
pub fn add_options<T>(self, section: &str) -> Self
自动绑定 appsettings 配置节到 T,并以 Arc<T> 注册到 DI 容器。
参考 ASP.NET Core 的 services.Configure<T>(configuration.GetSection(...)):
框架在 build() 时读取已合并的 appsettings(含 {Mode} overlay 与 env override),
取 section 子节点反序列化为 T,注册为单例供 handler 通过 Arc<T> 注入。
Host::builder()
.add_options::<SiteConfig>("Site")
.build()Sourcepub fn use_spa(self, source: impl Into<SpaSource>) -> Self
pub fn use_spa(self, source: impl Into<SpaSource>) -> Self
Serve SPA static files from a directory on disk.
Host::builder().use_spa("wwwroot").build()Runtime disk root — the directory next to the process (or under
app_base) where operators may drop overrides. This is not
build.rs web_root (that path only names what was baked in).
When the binary was built with #[webx::main(embed)] (and
build.rs wrote a table), that table is layered underneath this
directory at build: same-named disk files win.
Without (embed), only the disk directory is served.
Sourcepub fn no_spa(self) -> Self
pub fn no_spa(self) -> Self
Explicitly disable SPA, including auto-detection.
By default, the framework auto-detects wwwroot/ under app_base().
Call this when you want a pure API host without SPA fallback,
or in tests to isolate framework behavior from filesystem state.
pub fn use_cors(self, config: CorsConfig) -> Self
Sourcepub fn add_authentication(self) -> Self
pub fn add_authentication(self) -> Self
Register the JWT authentication service and middleware.
The ASP.NET Core AddAuthentication() + UseAuthentication() pair: it
enables JWT bearer authentication so endpoints that declare
#[authorize] receive claims. Route authorization itself is part of each
endpoint’s compile-time metadata and is always enforced after routing —
there is no second switch to turn it on.
Host::builder()
.add_authentication()
.build()Sourcepub fn add_localization(self) -> Self
pub fn add_localization(self) -> Self
Enable localization with the conventional resource layout.
Reads <culture>.json files from locales/ under the application base
(for example locales/zh-CN.json, locales/en.json). The active culture
is Culture.Default from appsettings (or APP__Culture__Default); it
decides the language of endpoint names, OpenAPI, and the endpoint
catalog.
Host::builder().add_localization().build()A missing locales/ directory is not an error; keys then fall back to
their literal or the key itself. For a single-file deployment, register
compiled-in resources with Self::add_localization_with.
Sourcepub fn add_localization_with(self, options: LocalizationOptions) -> Self
pub fn add_localization_with(self, options: LocalizationOptions) -> Self
Enable localization with explicit options.
Use this for compiled-in resources (include_str!) or a non-conventional
resource directory. Explicit resources override files with the same
culture and key.
Host::builder()
.add_localization_with(
LocalizationOptions::none()
.resources("zh-CN", include_str!("../locales/zh-CN.json"))
.resources("en", include_str!("../locales/en.json")),
)
.build()Sourcepub fn add_memory_cache(self) -> Self
pub fn add_memory_cache(self) -> Self
Register a memory cache instance for use via IDistributedCache trait.
The cache is registered as a singleton in the DI container.
Handlers can access it by implementing From<Arc<MemoryCache>>.
Host::builder()
.add_memory_cache()
.build()
.run().await;Sourcepub fn add_memory_cache_with(self, max_entries: usize) -> Self
pub fn add_memory_cache_with(self, max_entries: usize) -> Self
Register a memory cache with custom configuration.
Sourcepub fn use_middleware<T: IMiddleware + Default + 'static>(self) -> Self
pub fn use_middleware<T: IMiddleware + Default + 'static>(self) -> Self
Register a middleware by type in the default slot
(MiddlewareSlot::AfterAuth).
The default slot runs after authentication, so middleware that reads
ctx.claims() actually sees the principal. Use
Self::use_middleware_at to choose a different slot.
Host::builder()
.use_middleware::<TimingMiddleware>()
.build()Sourcepub fn use_middleware_at<T: IMiddleware + Default + 'static>(
self,
slot: MiddlewareSlot,
) -> Self
pub fn use_middleware_at<T: IMiddleware + Default + 'static>( self, slot: MiddlewareSlot, ) -> Self
Register a middleware by type in a specific pipeline slot.
Sourcepub fn use_middleware_with<F>(self, factory: F) -> Self
pub fn use_middleware_with<F>(self, factory: F) -> Self
Register a middleware with a custom factory function (default slot:
MiddlewareSlot::AfterAuth).
Use this when the middleware requires constructor parameters:
Host::builder()
.use_middleware_with(|| {
Arc::new(TimingMiddleware::new("api")) as Arc<dyn IMiddleware>
})
.build()Sourcepub fn use_middleware_with_at<F>(self, slot: MiddlewareSlot, factory: F) -> Self
pub fn use_middleware_with_at<F>(self, slot: MiddlewareSlot, factory: F) -> Self
Register a middleware with a custom factory in a specific pipeline slot.
Sourcepub fn add_health_check<F>(self, name: impl Into<String>, check: F) -> Self
pub fn add_health_check<F>(self, name: impl Into<String>, check: F) -> Self
Register a health check probe.
Health checks are exposed via /health and /health/ready endpoints
following RFC 8407 (application/health+json content type).
Host::builder()
.add_health_check("database", || -> HealthStatus {
if db_ping() { HealthStatus::pass() } else { HealthStatus::fail("db unreachable") }
})
.build()Sourcepub fn try_build(self) -> Result<Host>
pub fn try_build(self) -> Result<Host>
Build the host, reporting configuration problems as Err instead of
panicking.
This is the non-panicking form of HostBuilder::build. Production
guards (missing/weak JWT secret, wildcard CORS), a failing DI provider
build, invalid localization resources and inconsistent route/handler
metadata all come back as Error::Di carrying the same operator-facing
message HostBuilder::build panics with.
match Host::builder().mode(AppMode::Production).try_build() {
Ok(host) => host.run().await?,
Err(error) => eprintln!("invalid configuration: {error}"),
}Sourcepub async fn try_build_async(self) -> Result<Host>
pub async fn try_build_async(self) -> Result<Host>
Build the host, awaiting rust-dix’s build_async for async singletons.
Use this instead of HostBuilder::try_build when the service
collection contains async_* registrations (for example rust-ef’s
add_dbcontext_async). Async singletons are initialised dependency-first
by rust-dix before the host is assembled; failures surface as Error::Di.
let host = Host::builder()
.register(|svc| svc.add_dbcontext_async(|options| { /* ... */ }))
.try_build_async()
.await?;Sourcepub fn build(self) -> Host
pub fn build(self) -> Host
Build the host, panicking on configuration errors (fail fast at startup).
Equivalent to HostBuilder::try_build followed by a panic that keeps
the historical message, so a misconfigured deployment stops the process
instead of serving with weakened guards. Call try_build directly when
the caller wants to handle the error itself.