JasperFx / lamar

Fast Inversion of Control Tool and Successor to StructureMap
https://jasperfx.github.io/lamar
MIT License
563 stars 118 forks source link

Integration Testing Mode for easy runtime swapping of services #342

Open jeremydmiller opened 2 years ago

jeremydmiller commented 2 years ago

// cc @kkorotky

Request from one of our teams. Lamar is not nearly as flexible as StructureMap at runtime. This was a conscious decision on my part to improve performance and keep folks from shooting themselves in the foot and running to me for help when they did. The downside is that is that Lamar isn't that great for swapping in test services per test. You can use Injectable upfront, but that requires knowing which services will be swapped out ahead of time.

What if we had a mode where the container allowed for easier swapping at will, and reset all registrations back to the original registration with a single method call in a test fixture clean up? More investigation necessary. I'm thinking that in this mode Lamar uses QuickBuild() for everything so it's easier to swap things in and out.

jbogard commented 1 year ago

To piggyback, we have a common pattern in StructureMap:

  1. Create "blueprint" root container
  2. Create a nested container based on the root container
  3. Use Configure to swap out a dependency for a mokc
  4. Dispose the nested container

For .NET Core/5/6, we wind up using the WebApplicationFixture and OverrideServices stuff, but it forces us to rebuild the entire container every time. We do have well-known stubs injected into the container to swap out, like user sessions etc. But to do arbitrary mocking we have to rebuild the whole container.

jbogard commented 1 year ago

Was pointed to this: https://github.com/rsivanov/Rsi.DependencyInjection by @rsivanov, gonna try that out.

jbogard commented 1 year ago

Just to follow up, the strategy in the repo above doesn't work because it's trying to wrap the ServiceDescriptor instances in the service collection. However, Lamar populates those values with Lamar-specific things so the wrapped values are all wrong. Back to the drawing board.