WebApplicationFactory failing to replace registrations in Background Service
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 5h
- Merged PRs (30d)
- 276
Description
### Is there an existing issue for this?
- [X] I have searched the existing issues
### Describe the bug
I have run into an issue when trying to integration test a background service that listens to messages from RabbitMq. The issue is, after the first test runs, the subsequent test still has the same registration as the previous one.
I have created a project to illustrate the issue.
```
[Fact]
public async Task FirstTest1()
{
await SetupRabbitMq();
_fixture.BuildConsumerHttpClient((service) =>
{
service.Replace(ServiceDescriptor.Transient());
return true;
});
BasicPublish(new PublicationAddress(_rabbitMqClientConsumerConfiguration.ExchangeType, _rabbitMqClientConsumerConfiguration.LoggingExchangeName, string.Empty), "MessageTest1"u8.ToArray());
}
[Fact]
public async Task SecondTest2()
{
await SetupRabbitMq();
_fixture.BuildConsumerHttpClient((service) =>
{
service.Replace(ServiceDescriptor.Transient());
return true;
});
BasicPublish(new PublicationAddress(_rabbitMqClientConsumerConfiguration.ExchangeType, _rabbitMqClientConsumerConfiguration.LoggingExchangeName, string.Empty), "MessageTest2"u8.ToArray());
}
public class MessageTest1 : IMessage
{
public string Message => "MessageTest1";
}
public class MessageTest2 : IMessage
{
public string Message => "MessageTest2";
}
```
Here we set the service for each test to be MessageTest1 and MessageTest2 respectively along with the message that is sent from each test. Yet, as we can see in the Service, while it is receiving the message string "MessageTest2", the service registered is MessageTest1.

The tests use testcontainers to allow for easy running.
### Expected Behavior
_No response_
### Steps To Reproduce
https://github.com/Pastafarian/WebApplicationFactoryBugIssue
### Exceptions (if any)
_No response_
### .NET Version
8
### Anything else?
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.