2016-01-11 42 views
1

我們有一個非常基本的Owin應用程序,我們希望使用Ninject來解決我們的依賴關係。我想指出的是,沒有涉及Web API或MVC或其他中間件。Ninject範圍每Owin上下文

我們建立了這樣的內核:

private static StandardKernel CreateKernel() 
    { 
     var kernel = new StandardKernel(); 
     kernel.Bind<Test>().ToSelf().InRequestScope(); 
     kernel.Load(Assembly.GetExecutingAssembly()); 
     return kernel; 
    } 

Test類是簡化問題的更好的解釋。

我們試圖建立Ninject並註冊內核followoing:

app.UseNinjectMiddleware(CreateKernel); 

我真的不知道這是要走的路,但無法找到文件等類似的東西

我們想要的是在Owin請求的範圍內解析一個Test實例。假設我們有以下中間件:

app.Use((context,next) => 
      { 
       // How to access my Ninject Kernel or our test instance here? 
       return next.Invoke(); 
      }); 


app.Use((context,next) => 
       { 
        // How to access the same Ninject Kernel or our Test instance here? 
        return next.Invoke(); 
       }); 

有沒有人知道如何做到這一點???

回答

0

行,所以我想通了......

一切工作時我的Ninject.Web和Ninject.Web.Common的NuGet軟件包添加到我的項目如預期。

現在ik可以使用.InRequestScope(),並且每個請求都會創建一次(並共享)我的所有依賴項。同樣,IDisposable的所有實現都可以正確處理。它的工作方式與使用WebAPI或MVC時的工作方式相同。

1

查看NInject代碼後,我覺得NInject.Web.Common.OwinHost不應該在沒有WebApi或者其他附加組件的情況下工作。

實際上,InScope只有在某些組件實現INinjectHttpApplicationPlugin時才起作用,如下面的this code所示,並且此接口目前僅在特定的擴展中實現,例如MVC,WebApi或WCF。

所以我建議唯一的辦法就是實施你自己的INinjectHttpApplicationPlugin。在this postthis answer中有一些想法可能爲NInject的簡單範圍鑑別器提供構建塊。