I tried to inject a repository (service that uses DbContext to communicate with the database) into an Arduino communication service. The former has a Scoped lifetime because it is short-lived and instantiated on a per-request basis, every time it is needed, while the latter is Singleton because it's required to keep a persistent connection with the Arduino board during program execution.
Injecting it like this causes an unhandled exception, because it can lead to unexpected behaviours such as memory leaks, stale data etc. Changing the lifetime of either is not possible as it leads to other problems.
public ArduinoCommunicationService(IRoomsRepository roomsRepository)
{
_roomsRepository = roomsRepository;
}
1 Comment
Very nicely written!
I haven't tried to do this exactly, but one thing that might be missing: did you also need to register the factory at start-up, doing something like:
services.AddSingleton<IRoomsRepositoryFactory, RoomsRepositoryFactory>();
?If so, you could add how you did it, for completeness. You should be able to edit your post.