efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Unable to create a 'DbContext' of type ''. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Project3.Data.TestContext]' while attempting to activate 'Project3.Data.TestContext'.' was thrown while attempting to create an instance. For the different patterns supported at design time

Open ssccinng opened this issue 2 years ago • 15 comments

Ask a question

Remember:

I want to add database services in WPF through AddDbContext, but I found that this will result in migration failure

Include your code

https://github.com/ssccinng/TestEFWpf

Host = Microsoft.Extensions.Hosting.Host.
                     CreateDefaultBuilder().
                     UseContentRoot(AppContext.BaseDirectory).
                     ConfigureServices((context, services) =>
                     {

                         services.AddSingleton<MainViewModel>();
                         services.AddTransient<MainWindow>();
                         services.AddDbContext<TestContext>(option =>
                         {
                             option.UseSqlServer(context.Configuration.GetConnectionString("TestContextConnection"));
                         }, ServiceLifetime.Singleton, ServiceLifetime.Singleton);


                     })
                     .Build();

Include verbose output

Unable to create a 'DbContext' of type ''. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions1[Project3.Data.TestContext]' while attempting to activate 'Project3.Data.TestContext'.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728`

Include provider and version information

EF Core version:8.0.0 Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer) Target framework: (e.g. .NET 8.0) Operating system: IDE: (e.g. Visual Studio 17.9.0 Preview 3.0)

ssccinng avatar Jan 27 '24 01:01 ssccinng

Try removing the following from your AddDbContext call: ServiceLifetime.Singleton, ServiceLifetime.Singleton, to let the defaults apply. You're specifying singleton lifetime for your DbContext, which means that there will only be one DbContext instance in your entire application - that is almost surely not what you want.

roji avatar Jan 27 '24 06:01 roji

Try removing the following from your AddDbContext call: ServiceLifetime.Singleton, ServiceLifetime.Singleton, to let the defaults apply. You're specifying singleton lifetime for your DbContext, which means that there will only be one DbContext instance in your entire application - that is almost surely not what you want.

After removing it, it seems that it cannot be migrated

ssccinng avatar Jan 28 '24 05:01 ssccinng

@ssccinng you're going to have to post a minimal, runnable code sample for the migration error. In any case, specifying ServiceLifetime.Singleton for the context really is an error.

roji avatar Jan 28 '24 08:01 roji

https://github.com/ssccinng/TestEFWpf

https://github.com/ssccinng/TestEFWpf

It has been pushed to the project. Just now, what I meant was that removing these codes doesn't seem to make the migration successful

ssccinng avatar Jan 28 '24 08:01 ssccinng

https://github.com/ssccinng/TestEFWpf

https://github.com/ssccinng/TestEFWpf

It has been pushed to the project. Just now, what I meant was that removing these codes doesn't seem to make the migration successful

@roji

ssccinng avatar Jan 28 '24 08:01 ssccinng

Note for triage: this looks like a duplicate of #32835. That is, DbContext discovery doesn't work for non-ASP.NET applications that use hosting.

ajcvickers avatar Feb 01 '24 11:02 ajcvickers

An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: repository_pattern.Services.IAuthentication Lifetime: Scoped ImplementationType: repository_pattern.Services.AuthServices': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager1[repository_pattern.Model.ApplicationUser]' while attempting to activate 'repository_pattern.Services.AuthServices'.) Unable to create a 'DbContext' of type ''. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions1[repository_pattern.Data.DataContext]' while attempting to activate 'repository_pattern.Data.DataContext'.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 PM>

experiencing this error when trying to migrate

Tharyor07 avatar Apr 17 '24 12:04 Tharyor07

/cc @davidfowl More people struggling with your pattern here.

ajcvickers avatar Apr 17 '24 12:04 ajcvickers

I found that doing the migrations with the -v flag helps, as stated here. It seems that dotnet ef migrations will spit out this error for any error that might occur when migrating.

In my case I found out ef core migration can't read environment variables. I constructed my connection string using values I stored in the launchSettings.json's environmentVariables.

For anyone interested: To let ef core to read environment vars you need to manually export them like this:
export MY_VAR="my-value" Then optionally you can echo $MY_VAR to check if the current terminal session has the var.

Takobz avatar Jun 28 '24 13:06 Takobz

I am facing the same error here.

My project

Mode LastWriteTime Length Name


d----- 27/09/2024 21:36 .github d----- 02/10/2024 22:43 ContactZone.Api d----- 27/09/2024 21:16 ContactZone.Application d----- 27/09/2024 21:17 ContactZone.Domain d----- 02/10/2024 22:39 ContactZone.Infrastructure d----- 27/09/2024 21:21 ContactZone.Tests -a---- 27/09/2024 21:25 7258 .gitignore -a---- 27/09/2024 21:30 3220 ContactZone.sln -a---- 27/09/2024 21:25 20 README.md

my program.cs

using ContactZone.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Configure DbContext with connection string and specify migrations assembly
builder.Services.AddDbContext<ContactZoneDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("ContactZone"),
    b => b.MigrationsAssembly("ContactZone.Infrastructure")));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

My DbContext

using ContactZone.Domain.Domains;
using ContactZone.Infrastructure.Data.FluentMap;
using Microsoft.EntityFrameworkCore;

namespace ContactZone.Infrastructure.Data
{
    public class ContactZoneDbContext : DbContext
    {
        public DbSet<ContactDomain> Contatos { get; set; }
        public DbSet<ContactPersonalDataDomain> DadosPessoais { get; set; }

        public ContactZoneDbContext(DbContextOptions<ContactZoneDbContext> options)
           : base(options)
        {
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(new ContactMap());
            modelBuilder.ApplyConfiguration(new ContactPersonalDataMap());
        }
    }
}

My program is in ContactZone.Api and my dbContext in ContactZone.Infrastructure

When I try to migrate, I get this error. It looks there's no answer for it until now

MateusMo avatar Oct 03 '24 01:10 MateusMo

have you found answer?

dmitrygortex avatar Oct 08 '24 23:10 dmitrygortex

Reference in

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    // optionsBuilder.UseSqlServer(connectString); // Use this code when migrating
    base.OnConfiguring(optionsBuilder);
}

then delete at runtime

ssccinng avatar Oct 09 '24 01:10 ssccinng

I have solved the problem. It was easier than I thought.

Here the problem is on the nuget console the project selected wasn't the same project where my dbContext was. So I just changed and then I could execute the migration.

But I needed to click on the box to change the project, I tried to cd and It didn't work

MateusMo avatar Oct 09 '24 20:10 MateusMo

To those ones who have multiples projects that refer to the same solution, place this code inside a class within the same folder your data layer is:

Notice that ApplicationDbContext is the name I gave to the class I configured Entity Framework

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using System;

namespace App.Data.Context
{
    public class ContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
             
            // change if needed
            optionsBuilder.UseSqlServer("your connection string here");

            return new ApplicationDbContext(optionsBuilder.Options);

        }
    }
}

felipehimself avatar Oct 22 '24 20:10 felipehimself

Make sure that YourContext_DbContext is Concrete: Change YourContext_DbContext from an abstract class to a concrete class. You need to remove the abstract keyword and ensure it has a valid constructor. It worked for me to connect to postgress.

using Microsoft.EntityFrameworkCore;

namespace YourNamespace { public class YourContext_DbContext : DbContext //public abstract class YourContext_DbContext : DbContext - not OK ,delete abstract if it exists by mystake. { public YourContext_DbContext(DbContextOptions<YourContext_DbContext> options) : base(options) { }

    public virtual DbSet<**YourModelClass**> **YourModelClas**{ get; set; }
   //insert all your model classes.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        // Add any model configurations here
    }

    public static void InitialSeedDatabase(ModelBuilder modelBuilder)
    {
        // Seed data if needed
    }
}

}

SorinAlexandruMop avatar Oct 31 '24 12:10 SorinAlexandruMop