Skip to content

seeding data properly #67

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions src/Services/Catalog/Catalog.API/Data/CatalogContext.cs
Original file line number Diff line number Diff line change
@@ -11,9 +11,7 @@ public CatalogContext(IConfiguration configuration)
{
var client = new MongoClient(configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
var database = client.GetDatabase(configuration.GetValue<string>("DatabaseSettings:DatabaseName"));

Products = database.GetCollection<Product>(configuration.GetValue<string>("DatabaseSettings:CollectionName"));
CatalogContextSeed.SeedData(Products);
}

public IMongoCollection<Product> Products { get; }
14 changes: 11 additions & 3 deletions src/Services/Catalog/Catalog.API/Data/CatalogContextSeed.cs
Original file line number Diff line number Diff line change
@@ -7,12 +7,20 @@ namespace Catalog.API.Data
{
public class CatalogContextSeed
{
public static void SeedData(IMongoCollection<Product> productCollection)
public static void PrepPopulation(IApplicationBuilder app)
{
bool existProduct = productCollection.Find(p => true).Any();
using (var serviceScope = app.ApplicationServices.CreateScope())
{
SeedData(serviceScope.ServiceProvider.GetService<ICatalogContext>());
}
}

public static void SeedData(ICatalogContext catalogContext)
{
bool existProduct = catalogContext.Products.Find(p => true).Any();
if (!existProduct)
{
productCollection.InsertManyAsync(GetPreconfiguredProducts());
catalogContext.Products.InsertManyAsync(GetPreconfiguredProducts());
}
}

1 change: 1 addition & 0 deletions src/Services/Catalog/Catalog.API/Startup.cs
Original file line number Diff line number Diff line change
@@ -62,6 +62,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
});
CatalogContextSeed.PrepPopulation(app);
}
}
}