I am building a web api with asp.net and i am using the UnityContainer for handling dependencies.
For example, my auth controller can depends on the auth service:
class AuthController : ApiController {
private IAuthService authService;
public AuthController (IAuthService AuthService) {
this.authService = AuthService;
}
...
}
And the implementation of my auth service can depend on my user repository:
class AuthController : IAuthService {
private IUserRepository userRepository;
public AuthService (IUserRepository UserRepository) {
this.userRepository = UserRepository;
}
...
}
Now, i know that unity has two ways of handling dependencies, it can create a new instance of the dependency every time it is required, or it can save the instance of the dependency as a singleton and inject that same singleton every time the dependency is required.
By default, unity does it the first way (creates a new instance every time).
My question is: should i keep it that way, or should i tell unity to keep my services and repositories as singletons?
This question really came to my mind when my user repository depended on some other dependency, and that dependency depended on the user repository. When i tried to run the web api, it throw a stack over flow exception and i figured that it did this because it had to create a new instance of the user repository and the other repository every time.
Thank you, Arik