I am working on a POC and need some data. Decided to use the following as a template:
https://stormpath.com/blog/tutorial-entity-framework-core-in-memory-database-asp-net-core
Followed the example. Except at opt.UseInMemoerydatabase("Files"). without the name it shows error. This is my code. It throws
System.InvalidOperationException
HResult=0x80131509
Message=Cannot resolve scoped service 'DataAPI.Models.FileContext' from root provider.
at
var context = app.ApplicationServices.GetService<FileContext>();
Any one can suggest what am I doing wrong
namespace DataAPI
{
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)
{
// Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My DataAPI", Version = "v1" });
});
services.AddDbContext<FileContext>(opt =>
{
opt.UseInMemoryDatabase("Files");
});
services.AddControllers();
}
// 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.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My DataAPI V1");
});
var context = app.ApplicationServices.GetService<FileContext>();
AddTestData(context);
}
Here is the context class. File is a simple class with a few fields like id, name
namespace DataAPI.Models
{
public class FileContext: DbContext
{
public FileContext(DbContextOptions<FileContext> options)
: base(options)
{
}
public DbSet<File> Files { get; set; }
}
}
User contributions licensed under CC BY-SA 3.0