没有注册类型'Microsoft.AspNetCore.Hosting.IHostingEnvironment'的服务 [英] No service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' has been registered
问题描述
当我要为ASP MVC Core 2项目触发add-migration
命令时遇到问题.
I have a problem when I want to fire add-migration
command for a ASP MVC Core 2 project.
没有注册类型为'Microsoft.AspNetCore.Hosting.IHostingEnvironment'的服务.
No service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' has been registered.
这是我的 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();
}
}
上下文:
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);
}
}
这是我的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?
推荐答案
ASP.NET Core 2中有一个新的应用程序模式.请参见
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不再尝试直接调用Startup.ConfigureServices()
.在2.0版中,它将寻找静态的Program.BuildWebHost()
方法并从中获取您的应用程序服务.
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.
要采用新模式,请更新您的Program
类,使其看起来像这样.
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();
}
}
这篇关于没有注册类型'Microsoft.AspNetCore.Hosting.IHostingEnvironment'的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!