OWIN可以替换ASP.NET MVC应用程序中的DI吗?

大约一年前,在Visual Studio中创建时自动生成的MVC项目不包含任何关于OWIN的内容。 作为再次申请的人,试图理解变化,我想知道OWIN是否可以取代我的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.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(); // The ApplicationDbContextis retrieved like so return _userManager ?? HttpContext.GetOwinContext().GetUserManager(); } private set { _userManager = value; } } // Other things... } 

如果我理解正确的一切,我可以做的就是从使用StructureMap转移到OWIN(处理DI)只是构造我的控制器,如上面的AccountController。 有什么我缺少或做的我仍然需要我的申请DI / OWIN给我DI吗?

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

AccountController.UserManager的默认实现(以及一些其他AccountManager属性)演示了服务定位器作为反模式的示例。 所以我更喜欢删除所有内容并遵循DI原则。 此博客文章显示了如何重构默认项目模板以遵循这些原则。

我希望在下一版本的ASP.NET中改进dependency injection。 他们实际上承诺支持开箱即用的dependency injection。