Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Autofac-内存泄漏_C#_Entity Framework_Memory Leaks_Singleton_Autofac - Fatal编程技术网

C# Autofac-内存泄漏

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。它的实现方式如下(简化代码):


不幸的是,上下文没有正确处理。它停留在内存中的某个位置并导致泄漏。我不知道为什么。我在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()