C# Autofac-内存泄漏
我创建了简单的工厂来创建实体框架的DbContext。它的实现方式如下(简化代码):C# Autofac-内存泄漏,c#,entity-framework,memory-leaks,singleton,autofac,C#,Entity Framework,Memory Leaks,Singleton,Autofac,我创建了简单的工厂来创建实体框架的DbContext。它的实现方式如下(简化代码): 不幸的是,上下文没有正确处理。它停留在内存中的某个位置并导致泄漏。我不知道为什么。我在DbContext中重写了Dispose()方法,并调用了它。有人遇到过这样的问题吗?答案是在注册DbContext时使用.ExternallyOwned()扩展方法: builder .RegisterType<DbContext>() .AsImplementedInterfaces() .E
不幸的是,上下文没有正确处理。它停留在内存中的某个位置并导致泄漏。我不知道为什么。我在DbContext中重写了Dispose()方法,并调用了它。有人遇到过这样的问题吗?答案是在注册DbContext时使用.ExternallyOwned()扩展方法:
builder
.RegisterType<DbContext>()
.AsImplementedInterfaces()
.ExternallyOwned()
builder
.RegisterType()
.AsImplementedInterfaces()
.ExternallyOwned()
然后使用块将其包装在
中会导致对象的正确处理。OdynDbContext
是否实现了IDisposable
?您确定是DBContext导致内存泄漏吗?它可能是与数据库的连接,也可能与连接池有关。“它停留在内存中的某个位置并导致泄漏。”--你怎么知道它停留在内存中的某个位置?我想你有一个问题。尝试将ContextFactory
注册(及其所有父级)改为作用域或InstancePerDependence。
builder
.RegisterType<ContextFactory>()
.As<IContextFactory>()
.SingleInstance();
builder
.RegisterType<OdynDbContext>()
.AsImplementedInterfaces()
.InstancePerDependency();
public TestClass
{
private readonly IContextFactory _contextFactory;
public TestClass(IContextFactory contextFactory)
{
_contextFactory = contextFactory;
}
public void TestMethod()
{
using(var context = _contextFactory.CreateContext())
{
... operations on context
}
}
builder
.RegisterType<DbContext>()
.AsImplementedInterfaces()
.ExternallyOwned()