How do I get an instance of IAppBuilder elsewhere in my ASP.NET MVC 5.2.3 application?

巧了我就是萌 提交于 2019-11-30 12:12:16

You could simply inject AppBuilder itself to OwinContext. But since Owin context only supports IDisposable object, wrap it in IDisposable object and register it.

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.

public class FooController : Controller
{
    public ActionResult BarAction()
    {
        var app = HttpContext.GetOwinContext().Get<AppBuilderProvider>().Get();
        // rest of your code.        
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!