seesharper/LightInject.Microsoft.Hosting

Attempt to create a scoped instance outside a scope.

Opened this issue · 2 comments

If I inject the container and use it to create a scoped instance,

public class TestController : ControllerBase {
         IServiceContainer ServiceContainer { get; }
         public TestController(IServiceContainer serviceContainer) {
             this.ServiceContainer = serviceContainer;
         }
         [HttpGet]
         public object Get() {
             return ServiceContainer.GetInstance<TestResult>();
         }
     }

I get the error

Exception has occurred: CLR/System.InvalidOperationException
An exception of type 'System.InvalidOperationException' occurred in LightInject.dll but was not handled in user code: 'Attempt to create a scoped instance (TestLightInject.TestResult) outside a scope. If 'ContainerOptions.EnableCurrentScope=false',
the service must be requested directly from the scope. If ContainerOptions.EnableCurrentScope=true, the service can be requested from the container,
but either way the scope has to be started with 'container.BeginScope()''

This is by design. The container itself will always be a singleton and hence no scope is created.
This looks like an AspNet.Core app where the scope is started and ended automatically for us.
Instead of injecting the container, we should inject the services into the controller 👍

It works after I reverted back to LightInject.Microsoft.AspNetCore.Hosting 2.2.0.

I use LightInject to create objects from a common library. These objects may or may not be extended or overridden on a particular site. They aren't injectable, some of them are just plain old objects might which have additional properties to be passed on to the client. The correct implementation is registered in LightInject for each site, and created as needed by the container.

Also, I have a test controller which creates the other controllers for running tests. This fails without EnableCurrentScope = true.