commonsensesoftware / more-rs-di

Rust Dependency Injection (DI) framework
MIT License
20 stars 3 forks source link

Is there way for multiple threads to access service provider? #15

Closed anirudh1800 closed 10 months ago

anirudh1800 commented 10 months ago

I am building a http service and need multiple threads need to access ServiceProvider. Is there way for multiple threads to access service provider. Following is the error stack trace:-

fn parse_html(parser_input: Json<ParserInput>, service_provider: &State<ServiceProvider>) -> Json<ParserOutput> {
    |                                                                   ^^^^^^^^^^^^^^^^^^^^^^ `Rc<HashMap<di::Type, Vec<ServiceDescriptor>>>` cannot be shared between threads safely.
        = help: within `ServiceProvider`, the trait `Sync` is not implemented for `Rc<HashMap<di::Type, Vec<ServiceDescriptor>>>`
commonsensesoftware commented 10 months ago

There sure is. You just need to enable the async feature. This will result in the underlying collection being backed by Arc instead of Rc as well as implement Send + Sync. There's even a test that proves this behavior across threads:

https://github.com/commonsensesoftware/more-rs-di/blob/30b74e8cca6463ee78a2086d51476bfefd0438ed/src/di/provider.rs#L444

anirudh1800 commented 10 months ago

I enabled async featured and it worked. Thank you!