I’m encountering an issue with my ASP.NET Core Web API project. When trying to access data through the /api/StoryTelling endpoint, I’m getting the following error:
“Message”: “Unable to resolve service for type ‘WebAPI.Models.ZamanlaContext’ while attempting to activate ‘WebAPI.Controllers.StoryTellingController’.
Details:
In my Startup.cs file, I’ve configured the ZamanlaContext in the ConfigureServices method as follows:
public void ConfigureServices(IServiceCollection services)
{
var connectionString = _Configuration.GetConnectionString("ZamanlaDB");
services.Configure<IISOptions>(options => { });
services.AddDbContext<ZamanlaContext>(options =>
{
options.UseSqlServer(connectionString);
options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});
}
In my StoryTellingController.cs file, I have the following controller:
namespace WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StoryTellingController : ControllerBase
{
private readonly ZamanlaContext _context;
public StoryTellingController(ZamanlaContext context)
{
_context = context;
}
[HttpGet]
public IActionResult GetAllApprovedStories()
{
var stories = _context.StoryTelling
.Where(x => x.IsApproved)
.OrderByDescending(x => x.Id)
.ToList();
return Ok(stories);
}
}
}
And here’s my ZamanlaContext.cs file:
namespace WebAPI.Models
{
public class ZamanlaContext : IdentityDbContext<AppUser>
{
public ZamanlaContext(DbContextOptions options) : base(options)
{
}
public DbSet<Video> Video { get; set; }
public DbSet<Customers> Customers { get; set; }
public DbSet<StoryTelling> StoryTelling { get; set; }
public DbSet<UserRefreshToken> UserRefreshToken { get; set; }
public DbSet<FAQ> FAQ { get; set; }
public DbSet<NewsItems> NewsItems { get; set; }
public DbSet<Blog> Blog { get; set; }
}
}
The database connection is successful, but I’m unable to resolve the service for ZamanlaContext. What am I missing or doing wrong?
Adithya Srinivas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.