0

我有一个非常基本的WebAPI设置和令牌认证。
在应用程序开始我做的:
LightInject - 调用WebApi时没有作用域OWIN标识TokenEndpointPath

protected void Application_Start() 
{ 
    DependencyConfig.RegisterDependecis(); 
    //... 
    //... 
} 

的呼叫:

public class DependencyConfig 
{ 
    private static ServiceContainer _LightInjectContainer; 

    public static ServiceContainer LightInjectContainer 
    { 
     get { return _LightInjectContainer; } 
    } 

    public static void RegisterDependecis() 
    { 
     var container = new LightInject.ServiceContainer(); 
     container.RegisterApiControllers(); 
     container.ScopeManagerProvider = new PerLogicalCallContextScopeManagerProvider(); 
     container.EnableWebApi(GlobalConfiguration.Configuration); 

     container.Register<IRegistrationManager, RegistrationManager>(new PerScopeLifetime()); 

     _LightInjectContainer = container; 
    } 
} 

现在,当客户端调用令牌端点(请求令牌),供应商我这里定义:

OAuthOptions = new OAuthAuthorizationServerOptions 
{ 
    //... 
    //... 
    Provider = new SimpleAuthorizationServerProvider() 
    //... 
    //... 
}; 

正在使用此方法:

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider 
{ 
    //... 

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 
    { 
     //... 
     // Here I get the exception! 
     var registrationManager = DependencyConfig.LightInjectContainer.GetInstance<IRegistrationManager>(); 
     //... 
    } 

    //... 
} 

当我试图让该实例出现以下错误:

Attempt to create a scoped instance without a current scope.

我知道LightInject有开始/结束范围为每个请求的概念,它实际上是在告诉我,没有规模启动。但我似乎无法确定究竟是什么坏了,需要修复。

回答

1

通过阅读在this问题的最后答案,我想出了这个解决方案:(启动手动一个范围)

using(DependencyConfig.LightInjectContainer.BeginScope()) 
{ 
    IRegistrationManager manager = DependencyConfig.LightInjectContainer.GetInstance<IRegistrationManager>(); 
} 

Technicaly它的工作原理,但我不知道这是否是正确的解决方案关于幕后发生的事情。

+0

这将工作,除非您在管道中稍后请求另一个IRegistrationManager并期望它相同。范围是嵌套的,并且Web API将为您的控制器创建另一个范围。 – seesharper

+0

好的,但似乎是唯一的出路。您在另一个问题中回答的解决方案不起作用... –

+0

如果您查看LightInject.WebApi的文档,有一个示例shat显示如何使HttpRequestMessage在控制器外部可用。如果你根据这个例子实现这个,你应该能够到达HttpRequestMessage然后是DepenencyResolver。 http://www.lightinject.net/#webapi – seesharper

0

我LightInject的作者

你可以试试这个处理程序中(SimpleAuthorizationServerProvider)

request.GetDependencyScope().GetService(typeof(IRegistrationManager)) as IRegistrationManager;

其实没有理由,你应该揭露容器作为静态公共成员作为这使得开始使用服务定位器反模式变得非常容易。

查看此博客文章以获取更多信息。

http://www.strathweb.com/2012/11/asp-net-web-api-and-dependencies-in-request-scope/

+0

但是这不能编译。我唯一的“request”对象是context.Request,它是IOwinRequest类型的。 而GetDependencyScope()是HttpRequestMessage上的扩展。我怎样才能在这里得到这个对象? –

+0

你可以通过OwinContext.Environment获得HttpRequestMessage吗? – seesharper

+0

context.OwinContext.Environment是一个IDictionary 我浏览了它的所有条目,并试图将它们中的每一个都转换为HttpRequestMessage。 没有人会投。 –