1
votes

I am using Simple Injector in my ASP.NET WEb API project to dependency injection and OAuth for authentication. For that, I need to resolve an interface inside the GrantResourceOwnerCredentials method, like this:

using (IBusiness business = Injector.Container.GetInstance<IBusiness>())
{
}

But when it passes in that point, it shows me this error:

The Business is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope.

And I am configuring my container with this singleton method:

public class Injector
{
    private static Container container;

    public static Container Container
    {
        get
        {
            if (container == null)
            {
                container = new Container();
                container.Options.DefaultLifestyle = Lifestyle.Scoped;
                container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
            }

            return container;
        }
    }

    public static TInstance GetInstance<TInstance>() where TInstance : class
    {
        return Container.GetInstance<TInstance>();

    }
}

I am registering the dependencies with this code:

Injector.Container.Register<IBusiness, Business>(Lifestyle.Scoped);
1
This old answer is pretty much still the way to go. One might say this is a duplicate question...Ric .Net
Reading your question again, you're not showing all relevant code. I nowhere see any registration for IBusiness. Without such a registration the error Simple Injector throws will be very different than you're showing here. Please provide all relevant code.Ric .Net

1 Answers

1
votes

The problem was when I call the method Injector.Container.GetInstance<IBusiness>() inside GrantResourceOwnerCredentials, the container's scope was null and because of that, it throws that particular error. So it was necessary to initialize scope, and I did it using this code:

 using (SimpleInjector.Lifestyles.AsyncScopedLifestyle.BeginScope(Injector.Container))
 {
     using (IBusiness business = Injector.Container.GetInstance<IBusiness>())
     {
     }
 }

And change the defaultScopeLifestyle to hybrid, in the container class:

public static Container Container
        {
            get
            {
                if (container == null)
                {
                    container = new Container();

                    container.Options.DefaultScopedLifestyle = Lifestyle.CreateHybrid(
                        new AsyncScopedLifestyle(), new WebRequestLifestyle());
                }

                return container;
            }
        }