Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 847
C Smith Avatar asked Oct 03 '17 14:10

C Smith


1 Answers

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>();
like image 89
Marc Harry Avatar answered Sep 17 '22 22:09

Marc Harry