![](/img/trans.png)
[英]Dependency Injection unable to resolve service for type in .NET Core Function App running in Azure
[英]Unable to resolve dependency when running dotnet core app from console
我正在使用Dotnet Core Web-api作為后端和Angular2作為前端編寫客戶端-服務器應用程序。 持久層使用EntityFramework Core訪問postgre數據庫。 為了嘗試我的應用程序,我添加了一個數據庫種子類來創建一些可以使用的測試數據。 在這堂課上,我的問題開始了。
當我從Visual Studio Code運行應用程序時,一切工作正常。 如果使用“ dotnet run”從終端啟動應用程序,則會收到以下異常:
Unhandled Exception: System.Exception: Could not resolve a service of type 'OpenGameListApp.Data.DbSeeder' for the parameter 'dbSeeder' of method 'Configure' on type 'OpenGameListApp.Startup'. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: connectionString
at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
at Microsoft.EntityFrameworkCore.NpgsqlDbContextOptionsExtensions.UseNpgsql(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 NpgsqlOptionsAction)
at OpenGameListApp.Startup.<ConfigureServices>b__4_0(DbContextOptionsBuilder options) in /home/noam/projects/dotnet/OpenGameListApp/src/Startup.cs:line 43
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.DbContextOptionsFactory[TContext](IServiceProvider applicationServiceProvider, Action`2 optionsAction)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.AspNetCore.Hosting.Internal.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
--- End of inner exception stack trace ---
at Microsoft.AspNetCore.Hosting.Internal.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at OpenGameListApp.Program.Main(String[] args) in /home/noam/projects/dotnet/OpenGameListApp/src/Program.cs:line 15
Startup.cs類的代碼:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services
services.AddMvc();
// Add entity framework
services.AddEntityFrameworkNpgsql()
.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(Configuration["Data:DefaultConnection:ConnectionString"]));
// Add database seeder
services.AddSingleton<DbSeeder>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder)
{
// Add logger
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// Rewrite all routing urls including the root one to the index.html file by adding the following rules
var rewriteOptions = new RewriteOptions().AddIISUrlRewrite(env.ContentRootFileProvider, "rewrite-rules.xml");
// Add iis url rewrite features to kestrel
// Note: the app.UseRewriter method must be called before app.UseDefaultFiles and app.UseStaticFiles
app.UseRewriter(rewriteOptions);
// In order for your Web app to serve a default page without the user having to fully qualify the URI,
app.UseDefaultFiles();
// Enable service of static files in wwwroot folder
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = (context) =>
{
// Disable caching for all static files
context.Context.Response.Headers["Cache-Control"] = Configuration["StaticFiles:Headers:Cache-Control"];
context.Context.Response.Headers["Pragma"] = Configuration["StaticFiles:Headers:Pragma"];
context.Context.Response.Headers["Expires"] = Configuration["StaticFiles:Headers:Expires"];
}
});
// Enable the use of asp.net mvc framework
app.UseMvc();
// Initialize auto mapper
Mapper.Initialize(cfg => cfg.CreateMap<Item, ItemViewModel>());
// Seed database
dbSeeder.SeedIt();
}
如果我從Startup類中刪除dbSeeder,則該異常消失。 如果有人可以向我指出這里發生的事情,我將不勝感激。
Martin Ullrich的評論為我指明了正確的方向:
似乎無法從配置中讀取連接字符串,因為對UseNpgsql()的調用引發了
確實無法從配置中讀取連接字符串。 在我的項目中,我有兩個不同的appsettings文件: appsettings.development.json
和appsettings.json
。 僅前者包含連接字符串。 當我在Visual Studio Code中運行應用程序時,它將在調試環境中啟動,因此能夠讀取連接字符串。
但是,使用dotnet run
從終端運行應用程序似乎可以在生產環境中運行該應用程序。 將終端中使用的環境更改為開發后( export ASPNETCORE_ENVIRONMENT=Development
),一切正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.