I need to build an Owin middle-ware object but not from within the Startup
class. I need to build it from within anywhere else in my code, so I need a reference to the AppBuilder
instance of the application. Is there a way to get that from anywhere else?
我需要构建一个Owin中间件对象,但不是在Startup类中。我需要从代码中的其他地方构建它,因此需要对应用程序的AppBuilder实例进行引用。有办法从其他地方得到吗?
1 个解决方案
#1
14
You could simply inject AppBuilder
itself to OwinContext
. But since Owin context only supports IDisposable
object, wrap it in IDisposable
object and register it.
您可以简单地将AppBuilder本身注入到OwinContext中。但是由于Owin上下文中只支持IDisposable object,将其封装在IDisposable object中并注册。
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
}
}
So in everywhere of your code you have access IAppBuilder
object.
所以在代码的任何地方你都可以访问IAppBuilder对象。
public class FooController : Controller
{
public ActionResult BarAction()
{
var app = HttpContext.GetOwinContext().Get<AppBuilderProvider>().Get();
// rest of your code.
}
}
#1
14
You could simply inject AppBuilder
itself to OwinContext
. But since Owin context only supports IDisposable
object, wrap it in IDisposable
object and register it.
您可以简单地将AppBuilder本身注入到OwinContext中。但是由于Owin上下文中只支持IDisposable object,将其封装在IDisposable object中并注册。
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
}
}
So in everywhere of your code you have access IAppBuilder
object.
所以在代码的任何地方你都可以访问IAppBuilder对象。
public class FooController : Controller
{
public ActionResult BarAction()
{
var app = HttpContext.GetOwinContext().Get<AppBuilderProvider>().Get();
// rest of your code.
}
}