ASP.NET Web Api Dependency Injection - Singleton or not

为君一笑 提交于 2019-12-23 17:06:51

问题


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



来源:https://stackoverflow.com/questions/32017112/asp-net-web-api-dependency-injection-singleton-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!