Spaxter
Spaxter
Explore posts from servers
CC#
Created by Spaxter on 8/9/2024 in #help
✅ Transient DbContext vs DbContextFactory
In EF Core, what is the difference between registering a transient DbContext vs a DbContextFactory for DI? In both cases the DbContext will be created on-demand and disposed when the operation is completed, right? Are there any clear indications on when to use which?
4 replies
CC#
Created by Spaxter on 6/19/2024 in #help
✅ EF Core - Not getting updated data from PostgreSQL table
I have the following method in my DbService.cs
public async Task<long?> GetLastDumpTimeStamp(string endpoint)
{
using (var context = await _dbContextFactory.CreateDbContextAsync())
{
DumpHistory? history = await context.DumpHistory.AsNoTracking().Where(row => row.Endpoint == endpoint).FirstOrDefaultAsync();
return history?.LastUpdate;
}
}
public async Task<long?> GetLastDumpTimeStamp(string endpoint)
{
using (var context = await _dbContextFactory.CreateDbContextAsync())
{
DumpHistory? history = await context.DumpHistory.AsNoTracking().Where(row => row.Endpoint == endpoint).FirstOrDefaultAsync();
return history?.LastUpdate;
}
}
Which returns a unix timestamp from a postgres table. However if I manually change the data in the column to a completely different number and call the method again I still get the old value prior to my manual change, even after restarting my app. Am I doing something wrong?
6 replies
CC#
Created by Spaxter on 6/18/2024 in #help
Method on DI service doesn't do anything
Hello, I have a .NET app using Dependency Injection. One of the services I am injecting is a service for handling database insertions etc. Right now I have two methods on this class, one of them works perfectly fine but the other doesn't do anything when called. This is the method:
public async Task ClearGames()
{
_logger.LogDebug("ClearGames called");
using (var context = await _dbContextFactory.CreateDbContextAsync())
{
_logger.LogDebug("Truncating games table...");
try
{
await context.TruncateAsync<DbGame>();
await context.SaveChangesAsync();
} catch (Exception e)
{
_logger.LogError("{error}", e);
throw;
}
_logger.LogDebug("Truncate finished");
}
}
public async Task ClearGames()
{
_logger.LogDebug("ClearGames called");
using (var context = await _dbContextFactory.CreateDbContextAsync())
{
_logger.LogDebug("Truncating games table...");
try
{
await context.TruncateAsync<DbGame>();
await context.SaveChangesAsync();
} catch (Exception e)
{
_logger.LogError("{error}", e);
throw;
}
_logger.LogDebug("Truncate finished");
}
}
And when calling them like this, I only see the debug logs from the second method. The first one doesn't seem to run at all despite being called
await _db.ClearGames();
await _db.InsertGames(games);
await _db.ClearGames();
await _db.InsertGames(games);
20 replies
CC#
Created by Spaxter on 6/17/2024 in #help
DbContextFactory check for valid connection on app startup
I have a .NET app where I'm currently using EF Core's DbContextFactory with Postgres. However I noticed that no matter what host I set in my connection string the app starts normally and no errors are thrown. Is it possible to validate the connection at startup?
builder.Services.AddDbContextFactory<DataContext>(options =>
{
options.UseNpgsql(postgresOptions.ConnectionString);
}
builder.Services.AddDbContextFactory<DataContext>(options =>
{
options.UseNpgsql(postgresOptions.ConnectionString);
}
2 replies
CC#
Created by Spaxter on 10/18/2023 in #help
✅ EF Core long running query causing concurrency issues
Hello. I have a .NET application that uses a DbContext with PostgreSQL. To test the performance of my app, I added a million rows to one of the tables. I noticed that it takes a pretty long time to fetch all of these rows, and if I run the method to get all the rows again before the previous query finishes, it throws the following exception: System.InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. This is an example of how it is set up currently:
private MyDbContext _dbContext;

public DbService(MyDbContext dbContext)
{
_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
}

// This method throws the excpetion if called again before the previous query is finished
public async Task<List<MyObj>> GetAllObjects()
{
return await _dbContext.MyTable.AsNoTracking().ToListAsync();
}
private MyDbContext _dbContext;

public DbService(MyDbContext dbContext)
{
_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
}

// This method throws the excpetion if called again before the previous query is finished
public async Task<List<MyObj>> GetAllObjects()
{
return await _dbContext.MyTable.AsNoTracking().ToListAsync();
}
9 replies
CC#
Created by Spaxter on 10/14/2023 in #help
✅ launchSettings.json being ignored completely
All of a sudden, my .NET Visual Studio project has stopped respecting my launchSettings.json file. No matter what profile I run the app with, it uses the ports 5000 and 5001. I have no idea how this happened or why. launchSettings.json
{
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
"publishAllPorts": true,
"useSSL": true
},
"WSL": {
"commandName": "WSL2",
"launchBrowser": true,
"launchUrl": "https://localhost:7272/swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_URLS": "https://localhost:7272;http://localhost:5109"
},
"distributionName": ""
}
},
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:48027",
"sslPort": 44314
}
}
}
{
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
"publishAllPorts": true,
"useSSL": true
},
"WSL": {
"commandName": "WSL2",
"launchBrowser": true,
"launchUrl": "https://localhost:7272/swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_URLS": "https://localhost:7272;http://localhost:5109"
},
"distributionName": ""
}
},
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:48027",
"sslPort": 44314
}
}
}
10 replies
CC#
Created by Spaxter on 10/14/2023 in #help
✅ Unit Testing HttpClient
Hello, I'm currently trying to write some unit tests for a class that uses an HttpClientFactory through DI. This is the just of what I'm doing in these tests:
private string myApiUrl = "https://www.some-api.com";
private IHttpClientFactory _httpClientFactory;
private Mock<HttpMessageHandler> _httpClientMock;

[SetUp]
public void SetUp()
{
_httpClientMock = new Mock<HttpMessageHandler>();
_httpClientMock.SetupRequest(HttpMethod.Post, $"{myApiUrl}/example").ReturnsResponse("Example response");

var httpClientFactoryMock = new Mock<IHttpClientFactory>();
httpClientFactoryMock.Setup(c => c.CreateClient("exampleApi")).Returns(new HttpClient(_httpClientMock.Object)
{
BaseAddress = new Uri(myApiUrl)
});

_httpClientFactory = httpClientFactoryMock.Object;
}
private string myApiUrl = "https://www.some-api.com";
private IHttpClientFactory _httpClientFactory;
private Mock<HttpMessageHandler> _httpClientMock;

[SetUp]
public void SetUp()
{
_httpClientMock = new Mock<HttpMessageHandler>();
_httpClientMock.SetupRequest(HttpMethod.Post, $"{myApiUrl}/example").ReturnsResponse("Example response");

var httpClientFactoryMock = new Mock<IHttpClientFactory>();
httpClientFactoryMock.Setup(c => c.CreateClient("exampleApi")).Returns(new HttpClient(_httpClientMock.Object)
{
BaseAddress = new Uri(myApiUrl)
});

_httpClientFactory = httpClientFactoryMock.Object;
}
But every test that uses the IHttpClientFactory throws the following exception:
System.InvalidOperationException: Handler did not return a response message.
System.InvalidOperationException: Handler did not return a response message.
10 replies