Owin在Structure Map配置之前运行

时间:2014-03-20 18:50:14

标签: asp.net-mvc owin

在使用OWIN的ASP.NET MVC 5项目中,我有以下内容:

[assembly: OwinStartup(typeof(MvcProj.Site.OwinStartup), "Configure")]

namespace MvcProj.Site {

  public partial class OwinStartup {
    public void Configure(IAppBuilder application) {

      UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);

      application.UseCookieAuthentication(new CookieAuthenticationOptions {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        CookieSecure = CookieSecureOption.SameAsRequest,
        LoginPath = new PathString(url.Action(MVC.User.SignIn())),
        ReturnUrlParameter = "redirect"
      });

      application.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

    } // Configure

  } // OwinStartup

}

如您所见,我正在定义登录路径,如下所示:

LoginPath = new PathString(url.Action(MVC.User.SignIn())),

我从StructureMap收到错误,说我没有定义ITranslator ......

实际上它是已定义的但我的所有控制器都基于BaseController:

public abstract class BaseController : Controller, ITranslator_ {

  public readonly ITranslator _translator;

  protected BaseController() {
    _translator = ObjectFactory.Container.GetInstance<ITranslator>();
  } // BaseController

  public String _(String value) {
    return _translator.Translate(value);
  } // _

}

所以我认为发生的是Owin在global.asax Application Start中运行我的IoC代码之前。

如果我删除代码行LoginPath = new PathString(url.Action(MVC.User.SignIn()))那么一切正常。

有人可以告诉我如何解决这个问题吗?

谢谢,

米格尔

1 个答案:

答案 0 :(得分:3)

Microsft.Owin.SystemWeb主机使用PreApplicationStartMethodAttributebootstrap itself,该Nancy运行在Application_Start方法之前。这就是你看到崩溃的原因。您需要将DI设置移至Startup类。

我从ASP.NET MVC切换到StructureMap.MVC4后,除了需要为MVC设置依赖项解析器之外,您的设置应该类似。为此,您需要安装JabbR,然后删除它添加的StructuremapMvc类,因为您的设置代码现在位于Startup类中。

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var container = SetupStructureMap();

        // sets up the mvc dependency resolver
        DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
        GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container);

        SetupAuth(app, container);
    }

    private static IContainer SetupStructureMap()
    {
        ObjectFactory.Initialize(x =>
        {
            // ...
        });

        return ObjectFactory.Container;
    }

    public static void SetupAuth(IAppBuilder app, IContainer container)
    {
        app.SetDataProtectionProvider(container.GetInstance<IDataProtectionProvider>());
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = Constants.AppAuthType,
            CookieHttpOnly = true,
            CookieName = "app.id",
            LogoutPath = new PathString("/logout"),
            Provider = container.GetInstance<ICookieAuthenticationProvider>(),
            ReturnUrlParameter = string.Empty
        });
    }
}

我的Startup课程基于{{3}}中的一个。