2015-11-20 64 views
0

与Simple Injector一起使用时,Asp .net和Identity的使用存在一些混淆。有一些关于OWIN如何反模式的文章以及asp.net基本模板有多糟糕!简单注射器注册ASP.NET身份和Web API

无论如何,我理解的最后一个问题是确保在生成用户身份令牌时,我们注入正确的依赖关系,同时坚持OWIN请求管道。

我可能还不熟悉Simple Injector或OWIN,但我尝试通过重写简单注入器注册来手动注册AccountController。

有人可以确认下列代码是否正确?我可以看到它在注册和登录的Visual Studio中工作。我可以使用相同的过程获取令牌并对不同的登录进行身份验证。但是在项目中使用之前要确定这是否正确。

public partial class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
     var container = new Container(); 
     container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle(); 
     container.RegisterWebApiControllers(GlobalConfiguration.Configuration); 
     container.Options.AllowOverridingRegistrations = true; 
     ApplicationUserManager um = new ApplicationUserManager(
      new UserStore<ApplicationUser>(new ApplicationDbContext())); 
     SecureDataFormat<AuthenticationTicket> sdt = 
      new SecureDataFormat<AuthenticationTicket>(
       new TicketSerializer(), 
       new DpapiDataProtectionProvider().Create("ASP.NET Identity"), 
       TextEncodings.Base64); 
     container.Register<AccountController>(
      () => new AccountController(um, sdt), Lifestyle.Singleton); 
     container.Options.AllowOverridingRegistrations = false; 

     container.Verify(); 
     app.Use(async (context, next) => 
     { 
      using (container.BeginExecutionContextScope()) 
      { 
       await next(); 
      } 
     }); 
     GlobalConfiguration.Configuration.DependencyResolver = 
      new SimpleInjectorWebApiDependencyResolver(container); 
     ConfigureAuth(app); 
    } 

回答

1

我看到一个错误,那就是既您ApplicationDbContextAccountController正在成为单身。这可能是您在开发过程中不会注意到的事情,但这会导致生产中出现问题。当您在新请求中重复使用相同的控制器实例时,MVC将抛出异常,并且DbContext中的数据将变得非常快速并且DbContext不是线程安全的。相反,您可以执行以下操作:

var sdt = new SecureDataFormat<AuthenticationTicket>(
    new TicketSerializer(), 
    new DpapiDataProtectionProvider().Create("ASP.NET Identity"), 
    TextEncodings.Base64); 

container.Options.AllowOverridingRegistrations = true; 

container.Register<AccountController>(() => 
    new AccountController(
     new ApplicationUserManager(
      new UserStore<ApplicationUser>(new ApplicationDbContext())), 
     sdt), 
    Lifestyle.Scoped); 

container.Options.AllowOverridingRegistrations = false; 
+0

yes correct。谢谢。尽管我必须做出一点小改变。默认的Lifestyle设置为transient,导致配置错误,即瞬态对象无法实现IDisposable。所以在我更改为Container.Register 中的LifeStyle.Scoped后,它看起来很好。但是,感谢您发现请求问题,这会造成严重的破坏。 – Muthu