我正在尝试将一个接口注入我的HomeController,我收到了这个错误:
InvalidOperationException:尝试激活时无法解析“Microsoft.Extensions.Configuration.IConfiguration”类型的服务
我的启动课程如下:
public Startup(IApplicationEnvironment appEnv)
{
var builder = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddEnvironmentVariables()
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options => options
.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
services.AddSingleton(provider => Configuration);
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
try
{
using (var serviceScope = app.ApplicationServices
.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
serviceScope.ServiceProvider
.GetService<ApplicationDbContext>()
.Database.Migrate();
}
}
catch { }
}
app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.Run((async (context) =>
{
await context.Response.WriteAsync("Error");
}));
}
和我的HomeController构造函数是:
public HomeController(IConfiguration configuration, IEmailSender mailService)
{
_mailService = mailService;
_to = configuration["emailAddress.Support"];
}
请告诉我哪里弄错了。
Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider,ISet`1 callSiteChain,ParameterInfo [] parameters,Boolean throwIfCallSiteNotFound)
答案 0 :(得分:30)
尝试将其作为IConfigurationRoot
而不是IConfiguration
注入:
public HomeController(IConfigurationRoot configuration
, IEmailSender mailService)
{
_mailService = mailService;
_to = configuration["emailAddress.Support"];
}
在这种情况下,行
services.AddSingleton(provider => Configuration);
相当于
services.AddSingleton<IConfigurationRoot>(provider => Configuration);
因为类的Configuration
属性是这样声明的,并且注入将通过匹配它注册的任何类型来完成。我们可以很容易地复制它,这可能会更清楚:
public interface IParent { }
public interface IChild : IParent { }
public class ConfigurationTester : IChild { }
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
IChild example = new ConfigurationTester();
services.AddSingleton(provider => example);
}
public class HomeController : Controller
{
public HomeController(IParent configuration)
{
// this will blow up
}
}
正如评论中提到的stephen.vakil一样,最好将配置文件加载到类中,然后根据需要将该类注入控制器。这看起来像这样:
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
您可以使用IOptions
界面获取这些配置:
public HomeController(IOptions<AppSettings> appSettings)
答案 1 :(得分:7)
在Core 2.0中,建议使用IConfiguration而不是IConfigurationRoot
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
来自https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/#add-configuration-providers
答案 2 :(得分:2)
将项目从.Net Core 1.x移动到2.0时,将所有IConfigurationRoot
更改为IConfiguration