Asp.Net Core 2 Using In memory database for Prototyping getting Cannot resolve scoped service

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

Question

I am using Asp.Net Core 2 with Entity Framework Core 2 using code first development. I am trying to setup an in memory database that gets called in the startup.cs so I don't have to worry if someone change the models, then having to update the database since I am still in prototyping. The article I was trying to follow is https://stormpath.com/blog/tutorial-entity-framework-core-in-memory-database-asp-net-core

I can get the article to work in Core 1 and then if I upgrade the package to core 2 after that is still works, but the project I am currently working on is already in core 2 and I keep getting at error when i try's to call var context = app.ApplicationServices.GetService<ApiContext>();. The error I get is

System.InvalidOperationException: 'Cannot resolve scoped service 'TestWebsite.DA.Repositories.ApiContext' from root provider.'

The Message in that exception is.

Cannot resolve scoped service 'TestWebsite.DA.Repositories.ApiContext' from root provider.

The code that i changed in the startup.cs is below.

    public void ConfigureServices(IServiceCollection services)
    {
        AutoMapperConfiguration.Configure();
        services.AddDbContext<ApiContext>(opt => opt.UseInMemoryDatabase("TestDatabase"));
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }


        var context = app.ApplicationServices.GetService<ApiContext>();
        AddTestData(context);

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

I was wondering if the article I am following is the best way to do it in entity core 2 or if there is a better way and if there is a better way what may that be.

1
4
10/3/2017 3:27:59 PM

Accepted Answer

Inject IServiceProvider serviceProvider into your configure method so its signature looks like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)

You should then be able to do:

var context = serviceProvider.GetService<ApiContext>();
10
10/3/2017 3:31:28 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