OWIN 能否在 ASP.NET MVC 应用程序中替换 DI

本文关键字:应用程序 替换 DI MVC NET ASP OWIN | 更新日期: 2023-09-27 18:31:29

大约一年前,在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>(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,看起来我们可以随时使用如下所示的代码访问用户管理器或数据库上下文

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 吗?

OWIN 能否在 ASP.NET MVC 应用程序中替换 DI

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

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

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