In my web application I have a stateful object which needs to be the same between requests, so I register it as a singleton:
services.AddSingleton<IGamePlay, GamePlay.GamePlay>();
Now, somewhere down the line, GamePlay needs to consume a MyDbContext, and I add this using the following, because I need to pass in a specific constructor parameter of type DbContextOptions<MyDbContext>
services.AddDbContext<MyDbContext>(options => options.UseInMemoryDatabase(databaseName: "testdb"));
However, this fails at runtime with the following error:
InvalidOperationException: Cannot consume scoped service 'MyDbContext' from singleton 'IGamePlay'.
How do I register a dependency with AddDbContext that works with a singleton dependency?
EDIT: (In reply to the comments) I've found plenty of answers, but none that solve the problem. I've ended up registering MyDbContext using services.AddSingleton<MyDbContext>(new MyDbContext(new DbContextOptionsBuilder<MyDbContext>().UseInMemoryDatabase(databaseName: "testdb").Options));. It seems to work. Will something break horribly all of the sudden if I do it this way?