如何在我的 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?

查看:19
本文介绍了如何在我的 ASP.NET MVC 5.2.3 应用程序中的其他地方获取 IAppBuilder 的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要构建一个 Owin 中间件对象,但不能从 Startup 类中构建.我需要从代码中的任何其他地方构建它,因此我需要引用应用程序的 AppBuilder 实例.有没有办法从其他地方得到它?

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?

推荐答案

您可以简单地将 AppBuilder 自身注入 OwinContext.但是由于 Owin 上下文只支持 IDisposable 对象,所以将其包裹在 IDisposable 对象中并注册.

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
    }
}

因此,您可以在代码的任何地方访问 IAppBuilder 对象.

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.        
    }
}

这篇关于如何在我的 ASP.NET MVC 5.2.3 应用程序中的其他地方获取 IAppBuilder 的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆