[英]No service for type <TYPE> has been registered
我正在研究一个 asp.net 核心 mvc 项目,并尝试将数据库 object 注入到视图中,以便在视图中从中检索一些东西。
我将 class 注入到 startup.cs 并使用了 @inject 但我仍然得到异常。
InvalidOperationException:未注册“DbServices.CredentialDb”类型的服务。
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
这是 Startup.cs 的 ConfigureServices 方法:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddIdentity<ApplicationUser, IdentityRole>(
options => options.User.AllowedUserNameCharacters = null)
.AddEntityFrameworkStores<AppDbContext>();
services.AddControllersWithViews();
services.AddDbContextPool<AppDbContext>(
options => options.UseSqlServer(
_config.GetConnectionString("AutoLoverDbConnection"),
x => x.MigrationsAssembly("AutoMatcherProjectAss"))
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddSingleton<ISessionManager, ClientSIdeSessionManager>();
services.AddHttpContextAccessor();
services.AddSession();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies
// is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(60); //You can set Time
options.Cookie.HttpOnly = true;
});
services.AddTransient<ISche, SchedulerImpl>();
services.AddTransient<IQueue, QueueImpl>();
services.AddTransient<SchedulerJob>();
services.AddTransient<IBotFactory, BotFactory>();
services.AddTransient<ICredentialDb, CredentialDb>();
services.AddSingleton(provider => _scheduler);
services.AddAuthentication().AddFacebook(options =>
{
options.AppId = APP_ID;
options.AppSecret = APP_SECRET;
options.SaveTokens = true;
});
_scheduler.Clear();
}
这是我添加数据库访问 class 的地方:
services.AddTransient<ICredentialDb, CredentialDb>();
这些是 HTML 视图页面中的注入:
@using Microsoft.AspNetCore.Identity;
@using DbServices
@inject CredentialDb DataAccess
@inject UserManager<ApplicationUser> signIn
问题是使用注入接口和具体的class来解决它。
services.AddTransient<ICredentialDb, CredentialDb>();
AddTransient(IServiceCollection)将ICredentialDb
类型的临时服务和实现类型CredentialDb
添加到指定的 IServiceCollection。 您可以按服务类型解析您的服务,如下面的代码所示:
@inject ICredentialDb DataAccess
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.