6

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 Answer 1

12

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>();
Sign up to request clarification or add additional context in comments.

1 Comment

Why app.ApplicationServices doesn't works anymore?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.