- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当我想为 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/
我正在尝试将 Outlook API 与我的 React 应用程序集成。当我尝试使用 microsoft-graph-client 实现身份验证时,遇到以下错误。 'ImplicitMSALAuthe
我正在尝试使用 Microsoft Graph Beta API 在 Microsoft Teams 中创建 channel 。在文档中,它说 channel 实体具有属性 IsFavoriteByD
我的目标很简单。我想使用图形 API 将自动聊天消息发送到 MS Teams channel 。 这似乎是图形 API 的测试版功能,仅在 Microsoft.Graph.Beta 中可用。 我已经阅
通过委派权限获取 Teams channel 消息时(用户是团队成员): https://graph.microsoft.com/beta/teams/ {team_id}/channels/{cha
我正在使用带有 OData 端点的 Web API 和 Entity Framework 创建一个 RESTful 服务。 Microsoft.AspNet.WebApi.OData 和 Micros
我可以通过对标题和作者姓名的评估查询(以及解释查询)获得良好的结果。 但是如果我想通过 DOI 查找论文怎么办? 我可以通过扩展元数据描述(在现有搜索的属性中)获取条目的DOI信息,但是由于扩展元数据
我正在尝试通过displayName查询用户,但是在同时使用C#SDK和Graph Explorer发送请求时,我无法转义单引号。 更新:在示例中不清楚,我遇到麻烦的搜索词是I' 查询示例: http
我在使用 Microsoft fakes 的解决方案中有一个单元测试项目,当我构建它时出现以下错误。它提示无法加载的 DLL 在磁盘上。我已经打开了 Fusion 日志记录,这表明绑定(bind)成功
我想创建一个应用程序,当用户在 MS Teams 中接到电话时会收到通知。我的意思是我想在来电事件上订阅一些东西,然后根据来电信息做一些事情。这可能吗?到目前为止,我在 SDK 中没有看到任何事件。
如果我开发一个网站,它是否会以相同的方式在 IE11、Chrome、Firefox 和 edge 上运行,还是我们需要专门为 IE11 编写代码?我没有 Windows 8,因此无法在边缘浏览器上测试
我几个月前为某些收件箱创建了一些订阅,系统成功收到了有关收到电子邮件的通知,订阅也定期更新以增加到期日期。这是我的订阅列表: https://graph.microsoft.com/v1.0/subs
如果我开发一个网站,它是否会以相同的方式在 IE11、Chrome、Firefox 和 edge 上运行,还是我们需要专门为 IE11 编写代码?我没有 Windows 8,因此无法在边缘浏览器上测试
如果 Edge 在某些机器上发生崩溃,我们需要检查日志以了解发生了什么情况。 最佳答案 Microsoft Edge 实际上是一个 Windows 进程,因此您应该能够在事件查看器中查看日志。此外,您
我已经将一些测试用例与项目中的单元测试相关联。该项目已构建并复制到共享上的放置位置。当我去运行这些测试时,由于作为这些测试的一部分包含的非托管 DLL 的 System.DllNotFoundExce
我对 asp.net 核心标识中的三个包感到困惑。我不知道彼此之间有什么区别。还有哪些是我们应该使用的? 我在 GitHub 上找到了这个链接,但我没有找到。 Difference between M
在我的 Windows 类库(由 MVC 网站使用)中,我安装了 NugetPackage Microsoft.SqlServer.Types (Spatial)。 现在,我正在使用 ado.net
我有一个简单的 web 应用程序,我在 Teams 中显示为一个应用程序。我已经在 App Studio 中进行了设置,一切都按我的预期工作,一切都很好。它正在显示我的网络应用程序,这就是我想要的。
有什么不同?它们都是业务管理解决方案。他们做的一样吗?一些不同的版本?他们使用同一个平台吗? 动态 Assets 净值 Microsoft Dynamics NAV 2009 is a compreh
如何制定包含非英语字符(例如日耳曼语Umlauts)的Microsoft Graph /myOrganization/users OData查询? 例子: 我的租户中有一个名为“ThomasMülle
我想创建一个类似于乐队附带的星巴克应用程序的应用程序。我想显示条形码。我可以在云端或本地设备上将条形码生成为 JPG 图像,但我需要能够在乐队的屏幕上显示它们。到目前为止,我还没有找到使用 Band
我是一名优秀的程序员,十分优秀!