AddDbContext is not a member of IServiceCollection .Net Framework

Viewed 209

I have a .Net Framework 4.8 Webforms application that I need to extend.

A decision was made by the company that all new works would be done in C# rather than VB, and all new projects would be a min .Net 2.0 Standard so that the webforms 4.8 project can be migrated over to a .Net Core \ .Net6 Web Application

It has no DI in place at the moment and I am looking at introducing IServiceCollection using something like this in the .Net Framework 4.8 Global.asax file

IServiceCollection services = new ServiceCollection();
services.AddScoped<ICsvDataReader, CsvDataReaderService>();
services.AddDbContext<ApplicationDBContext>(x =>
{
    x.ConfigureWarnings(w => w.Ignore(SqlServerEventId.SavepointsDisabledBecauseOfMARS));
    x.UseSqlServer(connectionString);
});
var defaultResolver = new DefaultDependencyResolver(services);
DependencyResolver.SetResolver(defaultResolver);

The problem I am having is that I am getting an error

AddDbContext is not a member of IServiceCollection

However, this is something that I thought was and is standard in IServiceCollection. When I saw I was wrong I have added a couple other nugets that I thought would do the trick.

Microsoft.EntityFramework.SqlServer EntityFramework

But this error still appears. I would be grateful for some pointers on what I need, or more importantly where I have gone wrong.

I am also open to the idea of using something like Unity or someother provider if that helps.

1 Answers

It means either one of two things:

  1. you are missing using Microsoft.Extensions.DependencyInjection declaration on the top of your C# file that gives the exception, as the EntityFrameworkServiceCollectionExtensions that contains this AddDbContext extension method lives in this namespace
  2. You are missing a reference to the Microsoft.EntityFrameworkCore NuGet package from your project.

Please note that only Microsoft Entity Framework Core versions up to 3.1.24 support .NET Standard 2.0. Any newer version requires at least .NET Standard 2.1 or .NET 6, but .NET Framework 4.8 does not support .NET Standard 2.1. This might actually be the problem. You might have concluded you added the newest version to your project, but either the NuGet installation failed, or the project is currently not compiling because it is incompatible with that NuGet package.

Related