I'm getting Error as Unable to resolve service for type for my project

asp.net asp.net-core asp.net-core-webapi c# entity-framework-core

Question

I am trying to create a basic asp.net core web api for CRUD operations with entity framework but I am getting the following error:

 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'.)

my code was

    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; }
    }
}

for db context

 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);
    }
}

for controllers

    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);
        }
    }
}

for 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
12/18/2019 4:28:12 PM

Popular Answer

Thank You so much for those who tried to help me i got it resolved by adding these lines in

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();
0
12/18/2019 5:39:45 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow