Beim Ausführen meiner asp.net core 2-Projekte wird folgende Fehlermeldung angezeigt:
InvalidOperationException: Der Dienst für den Typ 'Microsoft.EntityFrameworkCore.DbContext' konnte nicht aufgelöst werden, während versucht wurde, 'ContosoUniversity.Service.Class.StudentService' zu aktivieren.
Hier ist meine Projektstruktur:
-- solution 'ContosoUniversity'
----- ContosoUniversity
----- ContosoUniversity.Model
----- ContosoUniversity.Service
IEntityService (zugehöriger Code):
public interface IEntityService<T> : IService
where T : BaseEntity
{
Task<List<T>> GetAllAsync();
}
IEntityService (zugehöriger Code):
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>();
}
}
Entität :
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);
}
}
Schulkontext:
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; }
}
Und zum Schluss noch meine Startup.cs Klasse:
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?}");
});
}
}
Was muss ich tun, um dieses Problem zu lösen?
StudentService
erwartet DbContext
, der Container weiß jedoch nicht, wie er es basierend auf Ihrem aktuellen Start auflösen soll.
Sie müssen den Kontext entweder explizit zur Service Collection hinzufügen
Anlaufen
services.AddScoped<DbContext, SchoolContext>();
services.AddScoped<IStudentService, StudentService>();
Oder Aktualisieren Sie den Konstruktor StudentService
, um explizit einen Typ zu erwarten, den der Container auflösen kann.
StudentService
public StudentService(SchoolContext context)
: base(context)
{
//...
}
wenn dbcontext von system.data.entity. DbContext geerbt wird, wird es so hinzugefügt
services.AddScoped(provider => new CDRContext());
services.AddTransient<IUnitOfWork, UnitOfWorker>();
services.AddTransient<ICallService, CallService>();