No service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' has been registered

asp.net-core asp.net-core-2.0 c# entity-framework-core

Question

I have a problem when I want to fire add-migration command for a ASP MVC Core 2 project.

No service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' has been registered.

Here is my Startup.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; set; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContextPool<SampleArchContext>((serviceProvider, optionsBuilder) =>
        {
            optionsBuilder.UseInternalServiceProvider(serviceProvider); // It's added to access services from the dbcontext, remove it if you are using the normal `AddDbContext` and normal constructor dependency injection.
        });

        services.AddMvc(options =>
        {
            options.AllowEmptyInputInBodyModelBinding = true;
        }).AddJsonOptions(jsonOptions =>
        {
            jsonOptions.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
        });
    }

    public void Configure(
        ILoggerFactory loggerFactory,
        IApplicationBuilder app,
        IHostingEnvironment env)
    {

        if (env.IsDevelopment())
        {
            var builder = new ConfigurationBuilder()
             .SetBasePath(env.ContentRootPath)
             .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
             .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
             .AddEnvironmentVariables();
            Configuration = builder.Build();

            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
        app.UseFileServer(new FileServerOptions
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "bower_components")),
            RequestPath = "/bower_components",
            EnableDirectoryBrowsing = false
        });            
    }
}

Program.cs:

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;
                config.SetBasePath(env.ContentRootPath);
                config.AddInMemoryCollection(new[]
                       {
                         new KeyValuePair<string,string>("the-key", "the-value")
                       })
                       .AddJsonFile("appsettings.json", reloadOnChange: true, optional: false)
                       .AddJsonFile($"appsettings.{env}.json", optional: true)
                       .AddEnvironmentVariables();
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddDebug();
                logging.AddConsole();
            })
            .UseIISIntegration()
            .UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            })
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}

context:

public interface IContext
{
    DbSet<Person> Persons { get; set; }
    DbSet<Country> Countries { get; set; }
    DbSet<TEntity> Set<TEntity>() where TEntity : class;
    EntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
    int SaveChanges();
}
public class SampleArchContext : DbContext, IContext
{
    public SampleArchContext(DbContextOptions<SampleArchContext> options)
        : base(options)
    { }
    public DbSet<Person> Persons { get; set; }
    public DbSet<Country> Countries { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Country>(build =>
        {
            build.Property(category => category.Name).HasMaxLength(450).IsRequired();
        });
    }
    public override int SaveChanges()
    {
        var modifiedEntries = ChangeTracker.Entries()
            .Where(x => x.Entity is IAuditableEntity
                && (x.State == EntityState.Added || x.State == EntityState.Modified));

        foreach (var entry in modifiedEntries)
        {
            IAuditableEntity entity = entry.Entity as IAuditableEntity;
            if (entity != null)
            {
                string identityName = Thread.CurrentPrincipal.Identity.Name;
                DateTime now = DateTime.UtcNow;

                if (entry.State == EntityState.Added)
                {
                    entity.CreatedBy = identityName;
                    entity.CreatedDate = now;
                }
                else
                {
                    base.Entry(entity).Property(x => x.CreatedBy).IsModified = false;
                    base.Entry(entity).Property(x => x.CreatedDate).IsModified = false;
                }
                entity.UpdatedBy = identityName;
                entity.UpdatedDate = now;
            }
        }

        return base.SaveChanges();
    }
}
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<SampleArchContext>
{    
    public SampleArchContext CreateDbContext(string[] args)
    {
        var service = new ServiceCollection();
        service.AddOptions();
        //service.AddScoped<IHostingEnvironment, CustomHostingEnvironment>();
        service.AddSingleton<ILoggerFactory, LoggerFactory>();
        var serviceProvider = service.BuildServiceProvider();
        var hostingEnvirement = serviceProvider.GetRequiredService<IHostingEnvironment>();
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
           .SetBasePath(basePath: hostingEnvirement.ContentRootPath)
           //.SetBasePath(Directory.GetCurrentDirectory())
            .Build();
        service.AddSingleton(provider => configuration);
        serviceProvider = service.BuildServiceProvider();

        var builder = new DbContextOptionsBuilder<SampleArchContext>();
        var connectionString = configuration.GetConnectionString("AppDbContextConnection");
        builder.UseSqlServer(connectionString);
        return new SampleArchContext(builder.Options);
    }
}

And here is my appsetting.json :

appsetting.json :

{
  "ConnectionStrings": {
    "AppDbContextConnection": "Server=localhost; Database=CoreDbName;Trusted_Connection=True; MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

I've searched a lot but I couldn't found a solution to this problem, How can I fix it?

1
3
9/12/2017 10:52:23 PM

Popular Answer

There's a new application pattern in ASP.NET Core 2. See Migrating from ASP.NET Core 1.x to ASP.NET Core 2.0 for details.

EF Core no longer attempts to directly invoke Startup.ConfigureServices(). In version 2.0, it will look for a static Program.BuildWebHost() method and get your application services from that.

To adopt the new pattern, update your Program class to look like this.

public class Program
{
    public static IWebHost BuildWebHost(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;
                config.SetBasePath(env.ContentRootPath);
                config.AddInMemoryCollection(new[]
                       {
                         new KeyValuePair<string,string>("the-key", "the-value")
                       })
                       .AddJsonFile("appsettings.json", reloadOnChange: true, optional: false)
                       .AddJsonFile($"appsettings.{env}.json", optional: true)
                       .AddEnvironmentVariables();
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddDebug();
                logging.AddConsole();
            })
            .UseIISIntegration()
            .UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            })
            .UseStartup<Startup>()
            .Build();

        return host;
    }

    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }
}
2
9/12/2017 10:47:16 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow