在 OAuth GrantResourceOwnerCredentials 方法中使用简单注入器时出错
Error using Simple Injector inside OAuth GrantResourceOwnerCredentials method
我在我的 ASP.NET WEb API 项目中使用 Simple Injector 进行依赖注入和 OAuth 身份验证。为此,我需要在 GrantResourceOwnerCredentials
方法中解析一个接口,如下所示:
using (IBusiness business = Injector.Container.GetInstance<IBusiness>())
{
}
但是当它经过那个点时,它向我显示了这个错误:
企业注册为 'Async Scoped' 生活方式,但实例是在活动(异步范围)范围的上下文之外请求的。
我正在使用这种单例方法配置我的容器:
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>();
}
}
我正在使用此代码注册依赖项:
Injector.Container.Register<IBusiness, Business>(Lifestyle.Scoped);
问题是当我在 GrantResourceOwnerCredentials
中调用方法 Injector.Container.GetInstance<IBusiness>()
时,容器的范围为 null,因此,它会抛出该特定错误。所以有必要初始化作用域,我用这段代码做到了:
using (SimpleInjector.Lifestyles.AsyncScopedLifestyle.BeginScope(Injector.Container))
{
using (IBusiness business = Injector.Container.GetInstance<IBusiness>())
{
}
}
并将容器中的 defaultScopeLifestyle 更改为 hybrid class:
public static Container Container
{
get
{
if (container == null)
{
container = new Container();
container.Options.DefaultScopedLifestyle = Lifestyle.CreateHybrid(
new AsyncScopedLifestyle(), new WebRequestLifestyle());
}
return container;
}
}
我在我的 ASP.NET WEb API 项目中使用 Simple Injector 进行依赖注入和 OAuth 身份验证。为此,我需要在 GrantResourceOwnerCredentials
方法中解析一个接口,如下所示:
using (IBusiness business = Injector.Container.GetInstance<IBusiness>())
{
}
但是当它经过那个点时,它向我显示了这个错误:
企业注册为 'Async Scoped' 生活方式,但实例是在活动(异步范围)范围的上下文之外请求的。
我正在使用这种单例方法配置我的容器:
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>();
}
}
我正在使用此代码注册依赖项:
Injector.Container.Register<IBusiness, Business>(Lifestyle.Scoped);
问题是当我在 GrantResourceOwnerCredentials
中调用方法 Injector.Container.GetInstance<IBusiness>()
时,容器的范围为 null,因此,它会抛出该特定错误。所以有必要初始化作用域,我用这段代码做到了:
using (SimpleInjector.Lifestyles.AsyncScopedLifestyle.BeginScope(Injector.Container))
{
using (IBusiness business = Injector.Container.GetInstance<IBusiness>())
{
}
}
并将容器中的 defaultScopeLifestyle 更改为 hybrid class:
public static Container Container
{
get
{
if (container == null)
{
container = new Container();
container.Options.DefaultScopedLifestyle = Lifestyle.CreateHybrid(
new AsyncScopedLifestyle(), new WebRequestLifestyle());
}
return container;
}
}