简体   繁体   English

如何在Asp.Net Core DI上注入具有不同生命周期的同一个类?

[英]How can I inject same class with different Life Cycles on Asp.Net Core DI?

In the past, I used Unity Container to resolve my dependencies with Asp.Net MVC. 过去,我使用Unity容器通过Asp.Net MVC解决我的依赖关系。 Now I am planning to use the Asp.Net Core DI instead of Unity that doesn't have at the moment a viable way to integrate with Core, and I am trying to figure out which is the best way to inject the same class but with different life cycles. 现在,我计划使用Asp.Net Core DI而不是Unity,而Unity目前没有与Core集成的可行方法,并且我试图找出哪种方法是注入相同类的最佳方法,但是不同的生命周期。

Why? 为什么? My question itself is coming because more than one thread operating on a single Entity Framework context was not thread safe and in order to execute a separate query in another thread I need a separate instance of my DbContext for each thread instance. 我的问题本身来了,因为在单个Entity Framework上下文上运行的多个线程不是线程安全的,并且为了在另一个线程中执行单独的查询,我需要每个线程实例的DbContext单独实例。 My strategy with Unity was creating 2 UnityContainers, one that had all singleton classes and the other that was creating the instances per request. 我在Unity上的策略是创建2个UnityContainer,一个具有所有Singleton类,另一个正在根据请求创建实例。 So when I created the second query in a separate thread I just resolve it through the unity's instance created per request. 因此,当我在单独的线程中创建第二个查询时,我只是通过每个请求创建的unity实例来解决它。

With Asp.Net Core I would like to know: 有了Asp.Net Core,我想知道:

1- Which is the best way to solve my problem? 1-解决我的问题的最佳方法是什么?

2- If I choose the same strategy I would like to know how can I have the same Asp.Net Core DI twice?, maybe applying a CompositionRoot pattern to both "containers" 2-如果我选择相同的策略,我想知道我如何两次拥有相同的Asp.Net Core DI?也许对两个“容器”都应用了CompositionRoot模式

3-If I don't choose my strategy, which pattern I can use to resolve in the same container an instance of the same class with different life cycles, and which is the way to resolve them separately? 3-如果我不选择策略,可以使用哪种模式在同一个容器中解析具有不同生命周期的同一个类的实例,以及分别解决它们的方法是什么?

What you're asking for is unnecessary, really. 确实,您要的是不必要的。

When you add a DbContext in the ConfigureServices (using the services.AddDbContext<MyDbContext> extension method) method in the StartUp class of an ASP .NET Core application, by default is gets registered as with a scoped lifetime. 当您在ASP .NET Core应用程序的StartUp类的ConfigureServices (使用services.AddDbContext<MyDbContext>扩展方法)方法中添加DbContext时,默认情况下将其注册为具有作用域的生命周期。 The scoped lifetime is required to get around the thread safety issue you mention. 要避开您提到的线程安全性问题,就需要作用域生存期。

Of course, you can override this with AddDbContext by passing some additional parameters. 当然,您可以通过传递一些附加参数来使用AddDbContext覆盖它。 Or, you can register the context yourself. 或者,您可以自己注册上下文。 But, why would you want to(?). 但是,为什么要(?)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM