Efcore: EF Migration Error : Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions

Created on 24 Mar 2019  路  9Comments  路  Source: dotnet/efcore

Hi,
I've got exactly the same error https://github.com/aspnet/EntityFrameworkCore/issues/14905 while creating my first entity framework core project.
The command : dotnet ef migrations add _name_of_migration_

Here is the callstack:
PM> dotnet ef migrations add MyFirstMigration --project "PathOfMyProjectMyProject.csproj"

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Microsoft.EntityFrameworkCore.DbContext]' while attempting to activate 'MyProject.Data.MyDbContext'.

at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)

at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(Type serviceType, Type implementationType, CallSiteChain callSiteChain)

at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain)

at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, CallSiteChain callSiteChain)

at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)

at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor(Type serviceType)

at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)

at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)

at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)

at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)

at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_2.b__11()

at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)

at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)

at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)

at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)

at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0()

at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.b__0()

at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Microsoft.EntityFrameworkCore.DbContext]' while attempting to activate 'MyProject.Data.MyDbContext'.

Steps to reproduce

  • Create a new asp.net core api project
  • Add class MyDbContext:
public class MyDbContext : DbContext
    {
        public MyDbContext(DbContextOptions<DbContext> options) : base(options)
        {
        }

        public DbSet<Value> Values { get; set; }
    }

  • Value.cs:
    public class Value
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
  • In startup class, add the context:
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<MyDbContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

In appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=MyProject.db" 
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

-Package Manager Console

Install-Package Microsoft.EntityFrameworkCore.Sqlite
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 2.2.3
dotnet ef migrations add MyFirstMigration --project "PathOfMyProjectMyProject.csproj"

Further technical details

EF Core version: (found in project.csproj or packages.config)
Database Provider:
Operating system: Win64
IDE: Visual Studio 2017 15.9.8

The csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.2.3" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.3">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
    </PackageReference>
  </ItemGroup>

</Project>
closed-question customer-reported

Most helpful comment

@fanxiaoyuan The constructor of your context class needs to be:

C# public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }

All 9 comments

refering to https://github.com/aspnet/EntityFrameworkCore/issues/9547, error persists after added
ervices.AddScoped(sp => sp.GetService());

@fanxiaoyuan The constructor of your context class needs to be:

C# public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }

I had a similar issue and was able to get it fixed by following the solution above.

Commenting here in case someone else comes across this. It also gives this error if you are using an inmemory database. I had to change it to the real thing to add migrations

The above Solution results in Error CS1503 Argument 1: cannot convert from 'Microsoft.EntityFrameworkCore.DbContextOptions' to 'Microsoft.EntityFrameworkCore.DbContextOptions' at compile time for me.

Same for me as @cmonstoke Were you able to find a solution

Same for me as @cmonstoke Were you able to find a solution

I finally found a solution here: https://stackoverflow.com/questions/45791795/unable-to-resolve-service-for-type-applicationcontext

Basically don't bother with 'DbContextOptions< Context > options' and use 'DbContextOptions options' and it all just works.

@juganpeeris sorry been afk for a while and no I didn鈥檛 resolve this sorry.

.NET Core Version: 5
Entity Framework Core Version: 5

I had multiple projects, basically a Infrastructure project that contained the Configurations/Repository and the API project which had the Startup.cs that injected dependencies.

So, in the command, I had to specify the API project (because thats where the injection occurs), like this:

C:\some\folders\Infrastructure> dotnet ef migrations add -s ..\MyAPI_Project\ MyInitialMigration

Adding the -s flag helps entity framework find the startup project.

Evidence:

image

I hope this picture helps (it shows my project's structure):

image

I'm very sorry for my English

Was this page helpful?
0 / 5 - 0 ratings