如何在我的 ASP.NET MVC 5.2.3 应用程序的其他地方获取 IAppBuilder 的实例?
How do I get an instance of IAppBuilder elsewhere in my ASP.NET MVC 5.2.3 application?
我需要构建一个 Owin 中间件对象,但不是从 Startup
class 内部构建。我需要从代码中的其他任何地方构建它,因此我需要引用应用程序的 AppBuilder
实例。有没有办法从其他地方得到它?
您可以简单地将 AppBuilder
本身注入 OwinContext
。但是由于Owin context只支持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.
}
}
我需要构建一个 Owin 中间件对象,但不是从 Startup
class 内部构建。我需要从代码中的其他任何地方构建它,因此我需要引用应用程序的 AppBuilder
实例。有没有办法从其他地方得到它?
您可以简单地将 AppBuilder
本身注入 OwinContext
。但是由于Owin context只支持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.
}
}