具有单例依赖注入的 Entity Framework Core
我正在尝试将依赖注入与单例和 DBContext 一起使用。
在 .net 框架中,我可以执行类似的操作
public class MySingleton
{
private readonly Func<MyDbContext> _getContext;
public MySingleton(Func<MyDbContext> getContext)
{
_getContext = getContext;
}
}
但是,当我现在执行此操作时,出现以下错误:
无法解析类型“System.Func`1[MyDbContext]”的服务
我确实尝试将其添加到构造函数中。
public class MySingleton
{
private readonly Func<MyDbContext> _getContext;
public MySingleton(IServiceProvider serviceProvider)
{
_getContext =
() => (MyDbContext)serviceProvider.GetService(typeof(MyDbContext));
}
}
但是,serviceProvider
返回相同的实例,
如何在每次使用 MyDbContext
时创建一个新实例?
I am trying to use Dependency Injection with a singleton and DBContext.
In .net framework I can do something like this
public class MySingleton
{
private readonly Func<MyDbContext> _getContext;
public MySingleton(Func<MyDbContext> getContext)
{
_getContext = getContext;
}
}
However, when I do this now I get the following error:
Unable to resolve service for type 'System.Func`1[MyDbContext]'
I did try to add this to the constructor.
public class MySingleton
{
private readonly Func<MyDbContext> _getContext;
public MySingleton(IServiceProvider serviceProvider)
{
_getContext =
() => (MyDbContext)serviceProvider.GetService(typeof(MyDbContext));
}
}
However, serviceProvider
returns the same instance
How can I create a new instance of MyDbContext
every time I use it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当用女士解析单身人士时,Singleton 及其所有依赖项都是从根范围/容器中解析的。这就是为什么您会体验从注射
iserviceProvider
始终给出相同实例的行为的行为。该范围的实例范围为容器。换句话说,这个范围的实例隐含成为单身人士。女士di的封闭构图模型使得很难在单例内解决范围通过环境状态手动管理范围),因为使用环境组成模型。
实际上,这里有两个选择:
transient
> transient scopediservicescope
从组件的方法内部从该范围中解析范围内的组件。例如:When resolving a singleton with MS.DI, that singleton and all its dependencies are resolved from the root scope/container. This is why you experience the behavior where resolving the
MyDbContext
from an injectedIServiceProvider
always gives the same instance; that scoped instance is scoped to the container. In other words, that scoped instance implicitly became a singleton.MS.DI's Closure Composition Model makes it very hard to resolve scopes within singletons (without manually managing scopes through ambient state), because scopes are not available ubiquitously through ambient state, as is done using the Ambient Composition Model.
In practice, there are two options here:
Transient
orScoped
IServiceScope
from within the component's methods and resolve the scoped component from such scope. For instance: