我收到错误消息,因为无法为我的项目类型解析服务

时间:2019-12-18 16:14:08

标签: c# asp.net asp.net-core entity-framework-core asp.net-core-webapi

我正在尝试为使用实体框架的CRUD操作创建基本的asp.net core web api,但出现以下错误:

 InvalidOperationException: Unable to resolve service for type 
'Corewebapi.Models.MyDatabaseContext' while attempting to activate 'Corewebapi.Controllers.LibrariesController'. and System.AggregateException:
'Some services are not able to be constructed (Error while validating the 
service descriptor 'ServiceType: Corewebapi.Controllers.LibrariesController 
Lifetime: Transient ImplementationType: Corewebapi.Controllers.LibrariesController': Unable to resolve service for type
'Corewebapi.Models.MyDatabaseContext' while attempting to activate 'Corewebapi.Controllers.LibrariesController'.)

我的代码是

    using System;
using System.Collections.Generic;

namespace Corewebapi.Models
{
    public partial class Library
    {
        public int Bookid { get; set; }
        public string Bookname { get; set; }
        public int? Price { get; set; }
        public DateTime? Date { get; set; }
        public string Author { get; set; }
    }
}

用于数据库上下文

 using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace Corewebapi.Models
{
    public partial class MyDatabaseContext : DbContext
    {
        public MyDatabaseContext()
        {
        }

        public MyDatabaseContext(DbContextOptions<MyDatabaseContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Library> Library { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                optionsBuilder.UseSqlServer("Server=localhost;Database=MyDatabase;Trusted_Connection=True;");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Library>(entity =>
            {
                entity.HasKey(e => e.Bookid);

                entity.Property(e => e.Bookid).HasColumnName("bookid");

                entity.Property(e => e.Author)
                    .HasColumnName("author")
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.Bookname)
                    .HasColumnName("bookname")
                    .HasMaxLength(50)
                    .IsUnicode(false);

                entity.Property(e => e.Date)
                    .HasColumnName("date")
                    .HasColumnType("date");

                entity.Property(e => e.Price).HasColumnName("price");
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

对于控制器

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Corewebapi.Models;

namespace Corewebapi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LibrariesController : ControllerBase
    {
        private readonly MyDatabaseContext _context;

        public LibrariesController(MyDatabaseContext context)
        {
            _context = context;
        }

        // GET: api/Libraries
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Library>>> GetLibrary()
        {
            return await _context.Library.ToListAsync();
        }

        // GET: api/Libraries/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Library>> GetLibrary(int id)
        {
            var library = await _context.Library.FindAsync(id);

            if (library == null)
            {
                return NotFound();
            }

            return library;
        }

        // PUT: api/Libraries/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        [HttpPut("{id}")]
        public async Task<IActionResult> PutLibrary(int id, Library library)
        {
            if (id != library.Bookid)
            {
                return BadRequest();
            }

            _context.Entry(library).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!LibraryExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Libraries
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        [HttpPost]
        public async Task<ActionResult<Library>> PostLibrary(Library library)
        {
            _context.Library.Add(library);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetLibrary", new { id = library.Bookid }, library);
        }

        // DELETE: api/Libraries/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<Library>> DeleteLibrary(int id)
        {
            var library = await _context.Library.FindAsync(id);
            if (library == null)
            {
                return NotFound();
            }

            _context.Library.Remove(library);
            await _context.SaveChangesAsync();

            return library;
        }

        private bool LibraryExists(int id)
        {
            return _context.Library.Any(e => e.Bookid == id);
        }
    }
}

staratup.cs

  using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Corewebapi.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Corewebapi
{
    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.AddConnections();
          //  services.AddDbContext<MyDatabaseContext>(options =>
            //    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 
            services.AddMvc()
                     .AddControllersAsServices();
            services.AddControllers().AddControllersAsServices();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

appsettings.json

    {
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

1 个答案:

答案 0 :(得分:0)

非常感谢那些试图帮助我的人,我通过在这些行中添加这些行来解决了

startup.cs

 services.AddConnections();
          services.AddDbContext<MyDatabaseContext>(options =>
            options.UseSqlServer(@"Server=localhost;Database=MyDatabase;Trusted_Connection=True;"));
            services.Configure<ConnectionString>(
        Configuration.GetSection(nameof(ConnectionString)));
            services.AddMvc()
                     .AddControllersAsServices();
            services.AddControllers().AddControllersAsServices();