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

后端 未结 1 1428
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 11:40

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

相关标签:
1条回答
  • 2020-12-31 12:03

    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.Current.GetOwinContext().Get<AppBuilderProvider>().Get();
            // rest of your code.        
        }
    }
    
    0 讨论(0)
提交回复
热议问题