使用Autofac MVC5应用解决IOwinContext [英] Resolving IOwinContext in MVC5 application using Autofac

查看:722
本文介绍了使用Autofac MVC5应用解决IOwinContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Membershi preBOOT 新ASP MVC5模板和 Autofac 麻烦。我已经使用了默认MVC5模板建立的网站,然后试图连线了 Membershi preBOOT 框架作为ASP的身份框架的替代品附带的模板。

I have trouble using MembershipReboot with the new ASP MVC5 template and Autofac. I have used the default MVC5 template to set up the site and then tried to wire up the MembershipReboot framework as a replacement for the ASP Identity framework that ships with the template.

我有这个问题是试图解决一个 IOwinContext Autofac 容器。下面是我在启动类(砍倒基础)接线。这是样品的 Membershi preBOOT Owin 应用程序中使用的布线(除了有他使用南希)。

This issue I am having is trying to resolve an IOwinContext from the Autofac container. Here is my wiring in the Startup class (cut down to basics). This is the wiring used in the samples for the MembershipReboot Owin application (except there he uses Nancy).

public partial class Startup
 {
    public void Configuration(IAppBuilder app)
    {
        var builder = new ContainerBuilder();
        builder.RegisterControllers(Assembly.GetExecutingAssembly());

        builder.Register(c => new DefaultUserAccountRepository())
            .As<IUserAccountRepository>()
            .As<IUserAccountQuery>()
            .InstancePerLifetimeScope();

        builder.RegisterType<UserAccountService>()
            .AsSelf()
            .InstancePerLifetimeScope();

        builder.Register(ctx =>
        {
            **var owin = ctx.Resolve<IOwinContext>();** //fails here
            return new OwinAuthenticationService(
                MembershipRebootOwinConstants.AuthenticationType,
                ctx.Resolve<UserAccountService>(),
                owin.Environment);
        })
            .As<AuthenticationService>()
            .InstancePerLifetimeScope();

        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

        ConfigureAuth(app);
        app.Use(async (ctx, next) =>
        {
            using (var scope = container.BeginLifetimeScope(b =>
            {
                b.RegisterInstance(ctx).As<IOwinContext>();
            }))
            {
                ctx.Environment.SetUserAccountService(() => scope.Resolve<UserAccountService>());
                ctx.Environment.SetAuthenticationService(() => scope.Resolve<AuthenticationService>());
                await next();
            }
        });
    }

这是我的控制器,控制器构造函数中指定的依赖。

And here is my controller with the dependency specified in the controller constructor.

public class HomeController : Controller
{
    private readonly AuthenticationService service;

    public HomeController(AuthenticationService service)
    {
        this.service = service;
    }

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";

        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";

        return View();
    }
}

看来我需要换我 Autofac 容器在 AutofacDependencyResolver 为了MVC框架使用集装箱解决组件。这是从南希Owin 样品唯一的主要区别和我MVC5使用。

It seems I need to wrap my Autofac container in an AutofacDependencyResolver in order for the MVC framework to use the container to resolve components. This is the only major difference from the Nancy Owin sample and my use in MVC5.

当我做到这一点,那么似乎(从我跟踪),如果依赖正在不通过 OWIN中间件叠加,让<$ C $首先要解决C> IOwinContext 从未注册。

When I do this, it then seems (from my Tracing) as if the dependency is being resolved without first going through the OWIN middleware stack so the IOwinContext is never registered.

我在做什么错在这里?

更新:

布洛克,你的新样本完美的作品,当我在迁移的配置,我的项目。只是我的理解,似乎这行你的新样本与容器注册当前OwinContext,这是什么pviously失踪$ P $。

Brock, your new sample works perfectly when I migrate the configuration over to my project. Just for my understanding, it seems that this line in your new sample registers the current OwinContext with the container and that is what was missing previously.

builder.Register(ctx=>HttpContext.Current.GetOwinContext()).As<IOwinContext>();

推荐答案

有是一条什么DI与AutoFac为MVC中的新样本:

There's a newer sample that does DI with AutoFac for MVC:

<一个href=\"https://github.com/brockallen/BrockAllen.Membershi$p$pboot/blob/master/samples/SingleTenantOwinSystemWeb/SingleTenantOwinSystemWeb/Startup.cs\">https://github.com/brockallen/BrockAllen.Membershi$p$pboot/blob/master/samples/SingleTenantOwinSystemWeb/SingleTenantOwinSystemWeb/Startup.cs

看看这有助于。

如果你不想使用 HttpContext.Current ,你可以做这样的事情:

If you don't want to use HttpContext.Current you could do something like this:

app.Use(async (ctx, next) =>
{
    // this creates a per-request, disposable scope
    using (var scope = container.BeginLifetimeScope(b =>
    {
        // this makes owin context resolvable in the scope
        b.RegisterInstance(ctx).As<IOwinContext>();
    }))
    {
        // this makes scope available for downstream frameworks
        ctx.Set<ILifetimeScope>("idsrv:AutofacScope", scope);
        await next();
    }
}); 

这是我们内部做了一些我们的应用程序。你需要线了您的Web API服务解析器寻找idsrv:AutofacScope。 Tugberk有一个帖子在此:

This is what we're doing internally for some of our apps. You'd need to wire up your Web API service resolver to look for "idsrv:AutofacScope". Tugberk has a post on this:

<一个href=\"http://www.tugberkugurlu.com/archive/owin-dependencies--an-ioc-container-adapter-into-owin-pipeline\">http://www.tugberkugurlu.com/archive/owin-dependencies--an-ioc-container-adapter-into-owin-pipeline

这篇关于使用Autofac MVC5应用解决IOwinContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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