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。 沒有人會投。 –

相關問題