pub trait MakeService {
type Service;
type Error;
// Required method
fn make_via_ref(
&self,
old: Option<&Self::Service>,
) -> Result<Self::Service, Self::Error>;
// Provided method
fn make(&self) -> Result<Self::Service, Self::Error> { ... }
}
Expand description
A trait implemented by service factories to create instances of services that implement the Service
trait.
MakeService
enables flexible service chain construction with state migration between instances.
It’s particularly useful for managing stateful resources (e.g., connection pools) when updating
service configurations.
§Key Features
- State preservation and resource reuse between service instances
- Optional creation of services from scratch
- Efficient management of stateful resources across service updates
§Example Implementation
use std::convert::Infallible;
use service_async::{MakeService, Service};
struct MyService {
connection_pool: ConnectionPool,
config: Config,
}
struct MyServiceFactory {
config: Config,
}
impl MakeService for MyServiceFactory {
type Service = MyService;
type Error = Infallible;
fn make_via_ref(&self, old: Option<&Self::Service>) -> Result<Self::Service, Self::Error> {
Ok(match old {
Some(existing) => MyService {
connection_pool: existing.connection_pool.clone(),
config: self.config.clone(),
},
None => MyService {
connection_pool: ConnectionPool::new(),
config: self.config.clone(),
},
})
}
}
In this example, MyServiceFactory
implements MakeService
to create MyService
instances,
demonstrating how to reuse a connection pool when an existing service is provided.
Required Associated Types§
Required Methods§
Sourcefn make_via_ref(
&self,
old: Option<&Self::Service>,
) -> Result<Self::Service, Self::Error>
fn make_via_ref( &self, old: Option<&Self::Service>, ) -> Result<Self::Service, Self::Error>
Creates a new service, optionally using an existing service as a reference.
This method allows for sophisticated service creation logic that can reuse state from an existing service instance.
§Arguments
old
- An optional reference to an existing service instance.
§Returns
A Result
containing either the newly created service or an error.