2014-11-23 54 views
4

大约一年前,在Visual Studio中创建时自动生成的MVC项目没有包含OWIN。作为再次提出申请的人,想要了解这些变化,我想知道OWIN是否可以取代我的DI。OWIN可以在ASP.NET MVC应用程序中替换DI吗?

据我所知,Startup.Auth.cs中的这一点是集中创建用户管理器(处理身份)以及为应用程序创建数据库连接。

public partial class Startup 
{ 
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 
    public void ConfigureAuth(IAppBuilder app) 
    { 
     // Configure the db context and user manager to use a single instance per request 
     app.CreatePerOwinContext(ApplicationDbContext.Create); 
     app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 

     // Other things... 
    } 
} 

从一个非常有用的资料来源:http://blogs.msdn.com/b/webdev/archive/2014/02/12/per-request-lifetime-management-for-usermanager-class-in-asp-net-identity.aspx,它看起来好像我们可以用代码在任何时间访问用户管理器或的DbContext像下面

public class AccountController : Controller 
{ 
    private ApplicationUserManager _userManager; 

    public AccountController() { } 

    public AccountController(ApplicationUserManager userManager) 
    { 
     UserManager = userManager; 
    } 

    public ApplicationUserManager UserManager { 
     get 
     { 
      // HttpContext.GetOwinContext().Get<ApplicationDbContext>(); // The ApplicationDbContextis retrieved like so 
      return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();     
     } 
     private set 
     { 
      _userManager = value; 
     } 
    } 

    // Other things... 
} 

如果我没有理解错的一切,所有的我可以做从使用StructureMap到OWIN(处理DI)的操作,只是像上面的AccountController一样构造我的控制器。有什么我失踪或我仍然需要DI在我的应用程序/是否OWIN给我DI?

回答

6

我个人不喜欢使用OWIN解决依赖关系的想法。

默认实现AccountController.UserManager(以及其他AccountManager属性)演示了service locator as an anti-pattern的示例。所以我宁愿删除所有这些东西,并遵循DI原则。 This blog post显示了如何重构默认项目模板以遵循这些原则。

我希望在ASP.NET的下一个版本中依赖注入会得到改进。它们实际上是promised支持依赖注入开箱即用。

+0

伟大的链接,感谢您找到该博客文章! – Zac 2014-11-23 22:32:26

相关问题