Click here to Skip to main content
15,946,988 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

My app is working well. But when I try to create unit test, the entity framework is not working well

I am trying to make Unit Testing for my Entity Framework, but when I try to get data / write data from server I am getting this error:

System.ObjectDisposedException : Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'FB_SERVICEContext'.

What is the culprit actually? Need advice.

Unit Test:
public class FileControllerTests
    private DependencyResolver _dependencyResolver;
    public FileController _controller { get; set; }
    public FB_SERVICEContext _context { get; set; }
    public FileImageDataService _service { get; set; }
    public ParamAppService _param{ get; set; }
    public LogErrorService _logger { get; set; }
    public void Setup()
        var webHost = WebHost.CreateDefaultBuilder().ConfigureAppConfiguration((context, config) =>
            IHostEnvironment env = context.HostingEnvironment;
                // copy configuration files to output directory
                // default prefix for environment variables is DOTNET_
                .AddJsonFile($"appsettings.Development.json", optional: true);

        _dependencyResolver = new DependencyResolver(webHost);
        var oService = _dependencyResolver.GetService<FileImageDataService>();
        var oLogger = _dependencyResolver.GetService<LogErrorService>();
        var oParam = _dependencyResolver.GetService<ParamAppService>();
        var oConfig = _dependencyResolver.GetService<IConfiguration>();
        var builder = new DbContextOptionsBuilder<FB_SERVICEContext>()
        //var oContext = _dependencyResolver.GetService<FB_SERVICEContext>();
        _context = new FB_SERVICEContext(builder.Options);

        _service = oService;
        _param = oParam;
        _logger = oLogger;

        _controller = new FileController(oService, oLogger, _param);

    //public async Task PostTestAsync()
    //    var response = await _controller.GetAsync();
    //    Assert.Fail();

    public async Task GetByIdTestAsync()
        var response = await _controller.DownloadFileByFileName("DIRECTSALES", "F8C22188-28CC-48CF-8C20-786B6BD15B70.jpg");

What I have tried:

Startup :
services.AddDbContext<FB_SERVICEContext>(opt => opt.UseSqlServer(Configuration.GetSection("ConnectionString:SqlServer").Value));//.EnableSensitiveDataLogging(), ServiceLifetime.Transient);
Updated 16-Apr-23 21:35pm

1 solution

REcommend that you check the documentation: Overview of testing applications that use EF Core - EF Core | Microsoft Learn[^]

More information here, including YouTube instructional videos here: unit testing with entity framework - Google Search[^]
Share this answer
mtoha 17-Apr-23 3:47am    
this is great direction. thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900