gpt4 book ai didi

asp.net-mvc - ASP.Net Core MVC 依赖注入(inject)不起作用

转载 作者:行者123 更新时间:2023-12-02 12:06:59 26 4
gpt4 key购买 nike

我正在尝试将接口(interface)注入(inject)到我的 HomeController 中,但收到此错误:

InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate

我的启动类如下:

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)

最佳答案

尝试将其作为 IConfigurationRoot 而不是 IConfiguration 注入(inject):

 public HomeController(IConfigurationRoot configuration
, IEmailSender mailService)
{
_mailService = mailService;
_to = configuration["emailAddress.Support"];
}

在本例中,该行

services.AddSingleton(provider => Configuration);

相当于

services.AddSingleton<IConfigurationRoot>(provider => Configuration);

因为类上的 Configuration 属性是这样声明的,并且注入(inject)将通过匹配它注册的任何类型来完成。我们可以很容易地复制这个,这可能会让它更清楚:

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在评论中提到的,最好将配置文件加载到一个类中,然后根据需要将该类注入(inject)到 Controller 中。看起来像这样:

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

您可以使用 IOptions 界面获取这些配置:

public HomeController(IOptions<AppSettings> appSettings)

关于asp.net-mvc - ASP.Net Core MVC 依赖注入(inject)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36801831/

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