REST API:无法解析类型的服务

时间:2019-05-19 12:33:10

标签: c# api model-view-controller service

[EDIT]由于已将其标记为ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate的重复项,因此我确保要注入接口,而不是具体的类。

尝试运行后端时,我得到

InvalidOperationException: Unable to resolve service for type 'BrickerApi.Data.PostContext' while attempting to activate 'BrickerApi.Data.PostDataInitializer'.
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, bool throwIfCallSiteNotFound)

Exception: Could not resolve a service of type 'BrickerApi.Data.PostDataInitializer' for the parameter 'postDataInitializer' of method 'Configure' on type 'BrickerApi.Startup'.
Microsoft.AspNetCore.Hosting.Internal.ConfigureBuilder.Invoke(object instance, IApplicationBuilder builder)

我一步一步地遵循了我学校的指示,甚至将其与他们的解决方案进行了比较,我似乎找不到任何区别。

这是我的 start

namespace BrickerApi
{
  public class Startup
  {
    public Startup(IConfiguration configuration)
    {
      Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

      services.AddScoped<PostDataInitializer>();
      services.AddScoped<IPostRepository, PostRepository>();
      services.AddOpenApiDocument( c =>
      {
        c.DocumentName = "apidocs";
        c.Title = "Post API";
        c.Version = "v1";
        c.Description = "The Post API documentation description.";
      });
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, PostDataInitializer postDataInitializer)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }
      else
      {
        app.UseHsts();
      }

      app.UseHttpsRedirection();
      app.UseMvc();

      app.UseSwaggerUi3();
      app.UseSwagger();

      postDataInitializer.InitializeData();
    }
  }
}

这是 PostContext ,我不确定这里可能出什么问题,但是由于该错误提到了该类,因此我也可以发布它。

namespace BrickerApi.Data
{
  public class PostContext : DbContext
  {
    public PostContext(DbContextOptions<PostContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      base.OnModelCreating(modelBuilder);
      modelBuilder.Entity<Post>()
          .HasMany(p => p.Comments)
          .WithOne()
          .IsRequired()
          .HasForeignKey("PostId"); //Shadow property
      modelBuilder.Entity<Post>().Property(p => p.Author).IsRequired().HasMaxLength(50);
      modelBuilder.Entity<Post>().Property(p => p.Title).HasMaxLength(50).IsRequired();
      modelBuilder.Entity<Post>().Property(p => p.Body).IsRequired();
      modelBuilder.Entity<Post>().Property(p => p.Upvotes);
      modelBuilder.Entity<Post>().Property(p => p.Pieces);
      modelBuilder.Entity<Comment>().Property(c => c.Body);
      modelBuilder.Entity<Comment>().Property(c => c.Author);
      modelBuilder.Entity<Comment>().Property(r => r.CreationDate);

      modelBuilder.Entity<Post>().HasData(...);

      modelBuilder.Entity<Comment>().HasData(...);
    }

    public DbSet<Post> Posts { get; set; }
  }
}

这是我的 DataInitializer ,我不确定这里可能出什么问题,但是再次,由于错误提到了这一点,我可能会遗漏一些东西。

namespace BrickerApi.Data
{
    public class PostDataInitializer
    {
        private readonly PostContext _dbContext;

        public PostDataInitializer(PostContext dbContext)
        {
            _dbContext = dbContext;
        }

        public void InitializeData()
        {
            _dbContext.Database.EnsureDeleted();
            if (_dbContext.Database.EnsureCreated())
            {
                //seeding the database with Posts, see DBContext               
            }
        }
    }
}

0 个答案:

没有答案