gpt4 book ai didi

c# - 没有注册类型 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' 的服务

转载 作者:行者123 更新时间:2023-11-30 16:42:44 24 4
gpt4 key购买 nike

当我想为 ASP MVC Core 2 项目触发 add-migration 命令时遇到问题。

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
});
}
}

程序.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"
}
}
}

我搜索了很多,但找不到解决这个问题的方法,我该如何解决?

最佳答案

ASP.NET Core 2 中有一个新的应用程序模式。请参阅 Migrating from ASP.NET Core 1.x to ASP.NET Core 2.0了解详情。

EF Core 不再尝试直接调用 Startup.ConfigureServices()。在 2.0 版中,它将查找静态 Program.BuildWebHost() 方法并从中获取您的应用程序服务。

要采用新模式,请将您的 Program 类更新为如下所示。

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();
}
}

关于c# - 没有注册类型 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' 的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46150730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com