ForrestLyman
ForrestLyman

Reputation: 1652

C# / OSX with In Memory DB

I'm developing a C# based API on Mac and .net crashes when I attempt to access DbContext in the Startup / Configure function, following this tutorial: https://stormpath.com/blog/tutorial-entity-framework-core-in-memory-database-asp-net-core

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.AddDbContext<ApiContext>(opt => opt.UseInMemoryDatabase());
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        // configure strongly typed settings objects
        var appSettingsSection = Configuration.GetSection("AppSettings");
        services.Configure<AppSettings>(appSettingsSection);

        // configure jwt authentication
        var appSettings = appSettingsSection.Get<AppSettings>();
        var key = Encoding.ASCII.GetBytes(appSettings.Secret);
        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x =>
        {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

        // configure DI for application services
        services.AddScoped<IUserService, UserService>();
        services.AddScoped<IClientAccountService, ClientAccountService>();
        services.AddScoped<ISearchService, SearchService>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // global cors policy
        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());

        app.UseAuthentication();

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

        app.UseMvc();
    }

Its failing on line 86, where it attempts to get the ApiContext from the ApplicationServices:

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

With: Unhandled Exception: System.InvalidOperationException: Cannot resolve scoped service 'VimvestPro.Data.ApiContext' from root provider.

Upvotes: 5

Views: 395

Answers (1)

Eric Damtoft
Eric Damtoft

Reputation: 1423

You're directly resolving a scoped service from the application container which isn't allowed. If you add ApiContext as a parameter to the Configure method, it will generate a scope and inject the context into your method.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApiContext context)
{
  ...
  AddTestData(context);
  ...
}

Upvotes: 1

Related Questions