rust

Why am I getting "App state is not configured" in Ntex despite using App::state()?


I'm encountering an error while running my API server using Ntex:

Error Message:

App state is not configured, to configure use App::state()

I have already configured the application state using App::state(), but the error persists.


My Setup:

My server configuration is as follows

#[ntex::main]
async fn main() -> std::io::Result<()> {
    dotenv().ok();

    let pool = Arc::new(Mutex::new(database::establish_connection()));
    let addr = SocketAddr::from(([0, 0, 0, 0], 8082));

    let user_repository = Arc::new(Mutex::new(UserRepository::new(pool.clone())));
    let user_service = UserService::new(user_repository);

    HttpServer::new(move || {
        App::new()
            .state(user_service.clone())
            .service(handle_login)
            .service(handle_register)
            .wrap(Logger::default())
    })
    .bind(addr)?
    .run()
    .await
}

Here’s a link to my server configuration in main.rs:
GitHub Link to Code

Image Reference:

Error Screenshot


Steps to Reproduce:

  1. Clone the repository: mt-auth-service.

  2. Run the server using cargo run.

  3. Attempt to hit the /login endpoint (or any other endpoint).


Expected Behavior:

The server should process the request and return the appropriate response.


Actual Behavior:

The server throws the error mentioned above when processing the request.


Additional Information:

Any insights into why this might be happening or how to debug it further would be greatly appreciated!

Initially, my UserService struct was defined like this:

struct UserService {             
    repo: UserRepository,  
}

To address the issue, I refactored it to use a thread-safe wrapper:

struct UserService {
    repo: Arc<Mutex<UserRepository>>, 
}

I made a similar change to the UserRepository struct as well, wrapping its dependencies in Arc<Mutex<...>>.

Despite these changes, the error persists.


Solution

  • The error has been fixed as my imports were incorrect , I was not using use crate::controllers.., I was directly importing use controllers::.., The working code is at this commit