LightInject icon indicating copy to clipboard operation
LightInject copied to clipboard

IServiceFactory or other injection for BeginScope access

Open GrimGadget opened this issue 6 years ago • 0 comments

I searched already and see that the IServiceFactory injection topic was previously discussed and discarded as a DI anti-pattern. I understand the view point and don't generally disagree with it.

However, I have a need to call BeginScope() within a Service Fabric service to define the scope/lifetime of a request. The ServiceContainer is created and managed in a separate abstraction library that is used across a number of Service Fabric services, and the request scope for a process request doesn't really exist within the context of that library.

I need some mechanism to define a custom scope for use with a custom lifetime in this service, whether it be auto-registration of IServiceFactory or some other method.

The short version of the reason why is that there are multiple components in this service that use a common DbContext, which is not threadsafe. The service processes messages from Service Bus using an IMessageReceiver, so it may launch multiple message processors simultaneously.

A single processor instance can and should use a single DbContext across all components that it uses, but that DbContext should not be used in any other message processors that are running simultaneously. This defines my scope and instance lifetime for a single DbContext.

GrimGadget avatar May 31 '19 19:05 GrimGadget