Asp.net

如何在我的 ASP.NET MVC 5.2.3 應用程序的其他地方獲取 IAppBuilder 的實例?

  • August 26, 2020

我需要建構一個 Owin 中間件對象,但不是從Startup類中建構。我需要從程式碼中的其他任何地方建構它,所以我需要引用AppBuilder應用程序的實例。有沒有辦法從其他地方得到它?

您可以簡單地將AppBuilder自身注入到OwinContext. 但是由於 Owin 上下文只支持IDisposable對象,所以將它包裝在對像中IDisposable並註冊它。

public class AppBuilderProvider : IDisposable
{
   private IAppBuilder _app;
   public AppBuilderProvider(IAppBuilder app)
   {
       _app = app;
   }
   public IAppBuilder Get() { return _app; }
   public void Dispose(){}
}

public class Startup
{
   // the startup method
   public void Configure(IAppBuilder app)
   {
       app.CreatePerOwinContext(() => new AppBuilderProvider(app));
       // another context registrations
   }
}

因此,在您的程式碼的任何地方,您都可以訪問IAppBuilder對象。

public class FooController : Controller
{
   public ActionResult BarAction()
   {
       var app = HttpContext.Current.GetOwinContext().Get<AppBuilderProvider>().Get();
       // rest of your code.        
   }
}

引用自:https://stackoverflow.com/questions/31915099