Working with InMemory in ASP.NET Core 2.2

Using the InMemory provider in ASP.NET Core is very useful, especially in the early stages of development.

According to the documentation ,” the InMemory provider is useful when you want to test components using something that approximates connecting to the real database, without the overhead of actual database operations. “.

The whole point of using InMemory is to not think about databases when we start developing. InMemory just simulates a fake database for us and holds it in memory (InMemory) in the R.A.M of our system. It stays there the whole time the app is running and gets vanished the moment we stop it.

This gives us the opportunity to add default configuration – to seed the inmemory with default data. For example, in this post we would add default questions (for a Q&A app) which get created every time we run the app, so that we don’t have to manually fill the database with junk. They also get automatically removed when the app stops. How cool is that? And it’s not just questions – you could seed all of your entities with default data (users is a good example).

Let’s now see how to configure InMemory. Actually, in ASP.NET Core it is extremely easy think to do.

1. Create Question Entity

public class BaseEntity {
 public int Id { get; set; }
}

public class Question: BaseEntity {
 public string Title { get; set; }
 public string Description { get; set; }
}

2. Create new DbContext

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Question> Questions { get; set; }
}

3. Create class to seed data when app starts

public class ApplicationDbContextSeed
{
    public static async Task SeedAsync(ApplicationDbContext context)
    {
        var questionsList = new List<Question>
        {
            new Question
            {
                Title = "Sample Title 1", Description = "Sample Description 1"
            }
            , new Question
            {
                Title = "Sample Title 2", Description = "Sample Description 2"
            }
            , new Question
            {
                Title = "Sample Title 3", Description = "Sample Description 3"
            }

        };

        await context.Questions.AddRangeAsync(questionsList);
        await context.SaveChangesAsync();
    }
}

4. Configure Startup.cs to use the InMemory provider

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseInMemoryDatabase("InMemoryDb"));
}

5. Configure Program.cs

public static void Main(string[] args)
{
    var host = CreateWebHostBuilder(args).Build();
    var logger = host.Services.GetRequiredService<ILogger<Program>>();

    var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

    // Seed InMemory when in Development
    if (environment == EnvironmentName.Development)
    {
        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;

            try
            {
                var dbContext = services.GetRequiredService<ApplicationDbContext>();
                ApplicationDbContextSeed.SeedAsync(dbContext).Wait();
            }
            catch (Exception e)
            {
                logger.LogError(e.Message);
                throw;
            }
        }
    }

    host.Run();
}

And that’s it! It is that easy to configure and implement InMemory into your project.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *