ASP.NET网页API依赖注入 - 辛格尔顿与否

问题描述:

我建设有asp.net的Web API和我使用的UnityContainer处理的依赖关系。

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?

这个问题真的来到了我的脑海里,当我的用户信息库依赖于其他一些依赖,并依赖依赖于用户存储库。
当我试图运行Web API,它抛出一个堆栈过流例外,我想通它这样做是因为它必须建立用户信息库的每一次新的实例和其他存储库。

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

创建每Htt的prequest一套新的实例可能是你想要什么。这prevents你一些意想不到的副作用,如果事情得到一个实例中的缓存搞乱一些逻辑。如果范围是指在Htt的prequest水平,和你的依赖关系链依赖于某个库4不同的时代,他们都会共享库的同一个实例。

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.

下面是你如何能做到在统一:MVC, EF - DataContext的单个实例每个Web请求在Unity

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