vamsi saggurthi
vamsi saggurthi

Reputation: 71

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

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": "*"
}

Upvotes: 0

Views: 2675

Answers (2)

snnpro
snnpro

Reputation: 307

Just make sure you include the type you expect from from the DI container in the startup, for example: take this type InboundMessageDTO for instance. when you expect to receive an instance of InboundMessageDTO from the DI, you must configure it as follows: services.AddScoped();

when you expect to have a a collection of it, you configure it as follow: services.AddScoped<List>(); Then in the contructer you do the following:

private readonly List inboungMessagesDTO; private readonly InboundMessageDTO inboundMessage;

    public PaymentsHandler(List<InboundMessageDTO> _inboungMessagesDTO, InboundMessageDTO _inboundMessage)
    {
        this.inboungMessagesDTO = _inboungMessagesDTO;
        this.inboundMessage = _inboundMessage;
    }

Upvotes: 1

vamsi saggurthi
vamsi saggurthi

Reputation: 71

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

Upvotes: 0

Related Questions