An error occurred while accessing the Microsoft.Extensions.Hosting services when do first migrations
Asked Answered
C

23

58

I don't understand what wrong. I tried to make a simple crud in .net core mvc with a very simple model which has few fields.

These are my models:

    public class Employee
    {
        [Key] public int EmployeeId { get; set; }

        [Required] public string FistName { get; set; }

        [Required] public string LastName { get; set; }

        public int PositionId { get; set; }
        public virtual Position Position { get; set; }

    }
public class Position
    {
        [Key]
        public int PositionId { get; set; }
        public string PositionName { get; set; }
        public ICollection<Employee> Employees { get; set; }
    }

then I made app context:

public class EmployeeContext : DbContext
{
    public EmployeeContext(DbContextOptions<EmployeeContext> options)
        : base(options)
    {
    }

    public DbSet<Employee> Employees { get; set; }
    public DbSet<Position> Positions { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>()
            .HasOne(e => e.Position)
            .WithMany()
            .HasForeignKey(e => e.PositionId);
    }
}

and registered context in Startup.cs:

 public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<EmployeeContext>(item =>item.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);                
        }

may be need one more file code of .csproj and program.cs

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

  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <DebugType>full</DebugType>
  </PropertyGroup>


  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.CookiePolicy" Version="2.2.8" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.2.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.2">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.6" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.2">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="3.1.2" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.1" />
  </ItemGroup>

</Project>

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }

then I tried to do first migrate, but I see a very strange error Add-Migration FirstInit -verbose

Using project 'Crud'.
Using startup project 'Crud'.
Build started...
Build succeeded.
C:\.nuget\packages\microsoft.entityframeworkcore.tools\3.1.2\tools\net461\win-x86\ef.exe migrations add FirstInit --json --verbose --no-color --prefix-output --assembly C:\source\repos\Crud\Crud\bin\Debug\net461\Crud.exe --startup-assembly C:\source\repos\Crud\Crud\bin\Debug\net461\Crud.exe --project-dir C:\source\repos\Crud\Crud\ --language C# --working-dir C:\source\repos\Crud --root-namespace Crud
Using assembly 'Crud'.
Using startup assembly 'Crud'.
Using application base 'C:\source\repos\Crud\Crud\bin\Debug\net461'.
Using working directory 'C:\source\repos\Crud\Crud'.
Using root namespace 'Crud'.
Using project directory 'C:\source\repos\Crud\Crud\'.
Using configuration file 'C:\source\repos\Crud\Crud\bin\Debug\net461\Crud.exe.config'.
Using assembly 'Crud'.
Using startup assembly 'Crud'.
Using application base 'C:\source\repos\Crud\Crud\bin\Debug\net461'.
Using working directory 'C:\source\repos\Crud\Crud'.
Using root namespace 'Crud'.
Using project directory 'C:\source\repos\Crud\Crud\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding Microsoft.Extensions.Hosting service provider...
Using environment 'Development'.
System.TypeLoadException: There is no implementation of the GetItem method in the type "Microsoft.AspNetCore.Mvc.Razor.Internal.FileProviderRazorProjectFileSystem" from assembly "Microsoft.AspNetCore.Mvc.Razor, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60".
   в Microsoft.Extensions.DependencyInjection.MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngineServices(IServiceCollection services)
   в Microsoft.Extensions.DependencyInjection.MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder builder)
   в Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddMvc(IServiceCollection services)
   в Crud.Startup.ConfigureServices(IServiceCollection services) в C:\source\repos\Crud\Crud\Startup.cs:строка 38
--- End the stack trace from the previous location where the exception occurred ---
   в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   в Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
   в Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   в Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
   в Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: There is no implementation of the GetItem method in the type "Microsoft.AspNetCore.Mvc.Razor.Internal.FileProviderRazorProjectFileSystem" from assembly "Microsoft.AspNetCore.Mvc.Razor, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60".
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'EmployeeContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'EmployeeContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 ---> System.MissingMethodException:There are no parameterless constructors defined for this object..
   в System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
   в System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   в System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   в System.Activator.CreateInstance(Type type, Boolean nonPublic)
   в System.Activator.CreateInstance(Type type)
   в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_3.<FindContextTypes>b__13()
   --- End trace of internal exception stack ---
   в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_3.<FindContextTypes>b__13()
   в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   в Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   в Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   в Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   в Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   в Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type 'EmployeeContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

What's wrong with these 3 lines?

Cradle answered 6/3, 2020 at 10:10 Comment(7)
Have you installed Microsoft.EntityFrameworkCore.Design?Yoshikoyoshio
i install Microsoft.EntityFrameworkCore.Design and I see the same errorCradle
Could you share details about Program.cs file?Yoshikoyoshio
add in questionsCradle
Everything looks ok, Can you Add-Migration FirstInit -verbose and see if you can get any more detail?Yoshikoyoshio
I did, what can you say?Cradle
Check my answer, Hope its helps.Yoshikoyoshio
Y
74

EF calls CreateWebHostBuilder or BuildWebHost without running Main. So Iconfiguration is null.

Create new class which inherited from IDesignTimeDbContextFactory .

public class YourDbContext : DbContext
{
//Dbcontext implementation
}

public class YourDbContextFactory : IDesignTimeDbContextFactory<YourDbContext>
{
    public YourDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<YourDbContext>();
        optionsBuilder.UseSqlServer("your connection string");

        return new YourDbContext(optionsBuilder.Options);
    }
}

You are using a new .net core EF which uses IHostBuilder.(in an older version like yours the provider is IWebHostBuilder).

The tools first try to obtain the service provider by invoking the Program.CreateHostBuilder(), calling Build(), then accessing the Services property.

You can learn more about Design-time DbContext Creation from Here

It may happen from a condition in your startup file or while you are injecting. for example, you have a flag that checks if some variable in appsettings is true to use inmemory database instance.

EF needs to build the model and use the DbContext without starting the application. When EF invokes methods, your config services are still null that's why you get an error.

Make sure you have installed the package

Microsoft.EntityFrameworkCore.Tools

Yoshikoyoshio answered 9/3, 2020 at 14:27 Comment(10)
Great it works! Is there a way to use the args to pass the connection string rather having it hard coded ?Hawkins
@Hawkins check this link gist.github.com/tonysneed/…Yoshikoyoshio
It is also worth mentioning that in some cases such an error may occur if there is some DI class that has not been registered in the ConfigureServices of Startup.cs. This was it for my scenario.Amalbergas
@ShervinIvari Could you please take a look at #72151924Latreese
@Latreese You need to implement and inject the AddRoleValidator.Yoshikoyoshio
WebHostBuilder is the new. IHostBuilder is the old.Residue
Add Db connection through injecting IConfiguration rather than hardcoding.Fleischman
Ohhhhhhh tnks!It solves my problem!!!Estriol
@Fleischman I think injecting won't work as running migration will not create the DI container. Still need to read configurations like "IConfigurationRoot configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.Development.json", optional: false, reloadOnChange: true) .Build(); " Getting the BasePath is something I still have to work onIsoclinal
@Isoclinal No problem! Also is it worth mentioning that you can read configuration by assemblyYoshikoyoshio
B
11

My experience with this particular error has everything to do with running in powershell and not setting the appropriate environment variable for ASPNETCORE_ENVIRONMENT.

$env:ASPNETCORE_ENVIRONMENT = "Development"

Then:

Add-Migration...
Update-Database...
etc...

Billion answered 24/1, 2022 at 18:32 Comment(0)
L
9

As the accepted answer suggested:

EF calls CreateWebHostBuilder or BuildWebHost without running Main. So Iconfiguration is null.

But instead of using a more complex factory, You can use this simple solution by overriding OnConfiguring.

public class ApplicationDbContext : DbContext
{        
    public ApplicationDbContext() {
        
    }
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {            
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Chinook");
        }
    }

*Pay attention for not using the db connection string inside the source code (docs)

dotnet user-secrets set ConnectionStrings:Chinook "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Chinook"
dotnet ef dbcontext scaffold Name=ConnectionStrings:Chinook Microsoft.EntityFrameworkCore.SqlServer

also pay attention to use only one \ in the cli command line.

Ldopa answered 6/4, 2021 at 18:33 Comment(2)
This solution is much simpler and I can finally generate migrations, cheers!Eigenvalue
This wasn't exactly the solution in my case, but it inspired me to check the right spelling of the ConnectionString. It was mispelled, this was the reason of the error.Vinson
I
8

My error was

An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Value cannot be null. (Parameter 'path') Unable to create an object of type 'MainDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Run you application once. If you have runtime startup errors, you will get this error.

For me, I had a service reading a path from appSettings but I had forgot to provide the value in appSettings. So there is a Null Exception that was taking place while the application was starting up.

Indecisive answered 8/1, 2023 at 15:13 Comment(0)
T
4

In my case, I put the connection string to secrets.json for security reason, but I forgot to close the curly braces. After I closed the curly bracket, everything is working fine.

That may also happens if you don't close the curly braces on appsettings.json.

Trabzon answered 23/10, 2022 at 19:37 Comment(0)
L
2

I got the same error message, but it was due to a different type mistake, sharing with you all, it might be useful.

I injected the service incorrectly,

wrong injection : ---> services.AddIdentity<IdentityUser, IdentityUser>().AddEntityFrameworkStores<AppDbContext>();

correct way ---> services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<AppDbContext>();

Literati answered 7/1, 2022 at 9:35 Comment(0)
B
2

This problem was killing me for quite some time. With exactly the same project configuration, migrations work just fine on other machines and from time to time on mine too. After digging in projects and half the Internet finally found a solution. Just an empty constructor public ApplicationDbContext() {} solved the issue. Still no idea while it always works fine on other PCs. Hope this helps someone save some hours!

Balliett answered 22/9, 2022 at 21:36 Comment(0)
P
2

In my case the error occurred due to format issues in appsettings.json

Possessive answered 18/10, 2022 at 15:55 Comment(0)
W
1

In my case, I removed the arguments between the parentheses:

before:

services.AddDbContext<EmployeeContext>(item =>item.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

after:

services.AddDbContext<EmployeeContext>();

Following Docs

Wrennie answered 17/3, 2021 at 5:1 Comment(0)
B
1

In my case I just forgot to add my own extension class to Program.cs (.NET 6)

Bifrost answered 6/7, 2022 at 12:22 Comment(0)
I
1

In my case Npgsql.EntityFrameworkCore.PostgreSQL (7.X.X) version was greater than the Microsoft.EntityFrameworkCore.Tools version(6.x.x).

Downgrading Npgsql.EntityFrameworkCore.PostgreSQL's version solved the problem.

Iny answered 21/11, 2022 at 12:37 Comment(0)
B
0

Another possible scenario, make sure there is folder wwwroot in your MVC application.

This happened to me when using angular and MVC together in one project. Angular build directly to wwwroot, so when there are an error in angular build. It didn't re-create wwwroot.

Brachy answered 21/5, 2022 at 17:31 Comment(0)
R
0

In my case, although am using SQLite, so what I did was just to update the Microsoft.EntityFrameworkCore.Design to the latest

Rudin answered 28/11, 2022 at 4:39 Comment(0)
B
0

My error was

An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Could not find the resource "ef.g.resources" among the resources "Microsoft.EntityFrameworkCore.Tools.Properties.Resources.resources" embedded in the assembly "ef", nor among the resources in any satellite assemblies for the specified culture. Perhaps the resources were embedded with an incorrect name.

For me it was the App.g.i.cs file that is automatically generated. I had an image set to be a SplashScreen And when you set it as a splash screen it creates code in the App.g.i.cs file in the main method

eg SplashScreen splashScreen = new SplashScreen("images/splash.png"); splashScreen.Show(true);

So i changed the image to not be set to a splash screen and displayed it manually instead. That got around the error and allowed me to use the IDesignTimeDbContextFactory as suggested above

Bryanbryana answered 7/12, 2022 at 12:43 Comment(0)
P
0

In my case I was using host, user and password stored in environment variables. I had to restart my IDE for it to start picking those up after I added them.

Purposive answered 5/1, 2023 at 18:6 Comment(0)
B
0

enter image description here

Just make sure Open & close brackets are not missing in appsettings.json Fixed the error for me

Bensen answered 9/1, 2023 at 13:16 Comment(0)
K
0

In my case I was adding Identity on to existing database, the solution for me was to initialize the second context in the Program.cs file

Before:

builder.Services.AddDbContext<DataContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<CommonProjectContext>();

After:

builder.Services.AddDbContext<DataContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
builder.Services.AddDbContext<CommonProjectContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<CommonProjectContext>();
Kg answered 24/3, 2023 at 23:43 Comment(0)
C
0

In my case im geting this error

basically the error was that i haven't placed access specifer in dbcontext class Public specifer was missing

Carnage answered 2/9, 2023 at 4:27 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Plainclothesman
S
0

Sometimes such these problem solved by :

  1. closing your project
  2. delete bin and obj folders from your solutions
  3. re-open your project and build it, then try
Springs answered 15/11, 2023 at 14:14 Comment(0)
D
0

It works for me. Add "ApplyConfigurationsFromAssembly" like this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.ApplyConfigurationsFromAssembly(typeof(YourDBContext).Assembly);
}
Dropforge answered 27/2 at 12:36 Comment(0)
G
0

I didn't had a comma in the jason file as shown below in green.

enter image description here

Gowen answered 27/2 at 15:59 Comment(0)
T
0

syntax issue in appsetting.json file. Was missing a curly brace. Once added, update-database worked fine.

Tropism answered 7/4 at 9:29 Comment(0)
T
0

in my case i there was wrong injection while I was injecting Services Wrong Injection :

builder.Services.AddIdentity<ApplicationUser, IdentitySser>()
    .AddEntityFrameworkStores<AppDbContext>()
    .AddSignInManager()
    .AddRoles<IdentityRole>();

Correct Injection :

builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<AppDbContext>()
    .AddSignInManager()
    .AddRoles<IdentityRole>();

so the error is I was injecting IdentityUser Instead of IdentityRole in the AddIdentity Service

Tarsal answered 24/4 at 13:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.