ASP.NET Web Api Dependency Injection - Singleton o

2019-07-10 03:55发布

问题:

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

回答1:

Creating a new set of instances per HttpRequest is likely what you want. This prevents you from some unintended side effects messing up some logic if something gets cached within an instance. If you scope it at the HttpRequest level, and your dependency chain depends on a certain repository 4 different times, they'll all share the same instance of that repository.

Here is how you can do that in Unity: MVC, EF - DataContext singleton instance Per-Web-Request in Unity



回答2:

You should not use singleton for dbcontext. You can use per httprequest lifetime or per resolve lifetime. To add per request lifetime you can use nuget package Unity.WebAPI