[英]ASP.NET Core 2 Unable to resolve service for type Microsoft EntityFrameworkCore DbContext
When I run my asp.net core 2 projects I get the following error message:当我运行我的 asp.net core 2 项目时,我收到以下错误消息:
InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContext' while attempting to activate 'ContosoUniversity.Service.Class.StudentService'.
InvalidOperationException:尝试激活“ContosoUniversity.Service.Class.StudentService”时无法解析“Microsoft.EntityFrameworkCore.DbContext”类型的服务。
Here is my project structure:这是我的项目结构:
-- solution 'ContosoUniversity'
----- ContosoUniversity
----- ContosoUniversity.Model
----- ContosoUniversity.Service
IEntityService (related code) : IEntityService(相关代码):
public interface IEntityService<T> : IService
where T : BaseEntity
{
Task<List<T>> GetAllAsync();
}
IEntityService (related code) : IEntityService(相关代码):
public abstract class EntityService<T> : IEntityService<T> where T : BaseEntity
{
protected DbContext _context;
protected DbSet<T> _dbset;
public EntityService(DbContext context)
{
_context = context;
_dbset = _context.Set<T>();
}
public async virtual Task<List<T>> GetAllAsync()
{
return await _dbset.ToListAsync<T>();
}
}
Entity :实体:
public abstract class BaseEntity {
}
public abstract class Entity<T> : BaseEntity, IEntity<T>
{
public virtual T Id { get; set; }
}
IStudentService :学生服务:
public interface IStudentService : IEntityService<Student>
{
Task<Student> GetById(int Id);
}
StudentService :学生服务:
public class StudentService : EntityService<Student>, IStudentService
{
DbContext _context;
public StudentService(DbContext context)
: base(context)
{
_context = context;
_dbset = _context.Set<Student>();
}
public async Task<Student> GetById(int Id)
{
return await _dbset.FirstOrDefaultAsync(x => x.Id == Id);
}
}
SchoolContext :学校环境:
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
public DbSet<Course> Courses { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Student> Students { get; set; }
}
And finally here is my Startup.cs class :最后这是我的Startup.cs类:
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment env, IServiceProvider serviceProvider)
{
Configuration = configuration;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<SchoolContext>(option =>
option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IStudentService, StudentService>();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
What should I do to resolve this problem?我应该怎么做才能解决这个问题?
StudentService
expects DbContext
but the container does not know how to resolve it based on your current startup. StudentService
预计DbContext
,但容器不知道如何根据你当前的启动来解决它。
You would need to either explicitly add the context to the service collection您需要将上下文显式添加到服务集合
Startup启动
services.AddScoped<DbContext, SchoolContext>();
services.AddScoped<IStudentService, StudentService>();
Or update the StudentService
constructor to explicitly expect a type the container knows how to resolve.或者更新
StudentService
构造函数以明确期望容器知道如何解析的类型。
StudentService学生服务
public StudentService(SchoolContext context)
: base(context)
{
//...
}
I encountered a similar error ie我遇到了类似的错误,即
An unhandled exception occurred while processing the request.处理请求时发生未处理的异常。 InvalidOperationException: Unable to resolve service for type 'MyProjectName.Models.myDatabaseContext' while attempting to activate 'MyProjectName.Controllers.MyUsersController'.
InvalidOperationException:尝试激活“MyProjectName.Controllers.MyUsersController”时无法解析“MyProjectName.Models.myDatabaseContext”类型的服务。
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired) Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
What I later figured out was... I was missing the following line ie adding my database context to services:我后来发现的是......我错过了以下行,即将我的数据库上下文添加到服务:
services.AddDbContext<yourDbContext>(option => option.UseSqlServer("Server=Your-Server-Name\\SQLExpress;Database=yourDatabaseName;Trusted_Connection=True;"));
Here goes my ConfigureServices method defined in Startup class:这是我在 Startup 类中定义的 ConfigureServices 方法:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential
//cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext<yourDbContext>(option =>
option.UseSqlServer("Server=Your-Server-Name\\SQLExpress;Database=yourDatabaseName;Trusted_Connection=True;"));
}
...
...
}
Basically, when you generated model classes from database, all your database tables were mapped into respective Model classes by creating the "New Scaffolded Item" and choosing the appropriate database context during the scaffolding procedure.基本上,当您从数据库生成模型类时,通过创建“新脚手架项”并在脚手架过程中选择适当的数据库上下文,您的所有数据库表都被映射到相应的模型类中。 Now, you need to manually register your database context as a service to the
services
parameter of ConfigureServices
method.现在,您需要手动将您的数据库上下文作为服务注册到
ConfigureServices
方法的services
参数。
Btw, rather than hard coding your connection string, you'll ideally pick it up from the configuration data.顺便说一句,与其对连接字符串进行硬编码,不如从配置数据中提取它。 I have attempted to keep things simple here.
我试图在这里保持简单。
if dbcontext inherited from system.data.entity.如果 dbcontext 继承自 system.data.entity。 DbContext then it woud be added like that
DbContext然后它会像那样添加
services.AddScoped(provider => new CDRContext());
services.AddTransient<IUnitOfWork, UnitOfWorker>();
services.AddTransient<ICallService, CallService>();
This error is thrown when the options argument is null or cannot be retrieved using GetConnectionString().当 options 参数为 null 或无法使用 GetConnectionString() 检索时,将引发此错误。
I had this error because my appsettings.json file that defines my ConnectionStrings had an extra curly bracket } at the end.我有这个错误是因为我的 appsettings.json 文件定义了我的 ConnectionStrings 在末尾有一个额外的大括号 } 。
Stupid, but frustrating.愚蠢,但令人沮丧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.