【问题标题】:Can OWIN replace DI in a ASP.NET MVC application?OWIN 可以在 ASP.NET MVC 应用程序中替换 DI 吗?
【发布时间】:2014-11-23 03:19:25
【问题描述】:

大约一年前,在 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,似乎我们可以随时使用如下代码访问用户管理器或 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?

【问题讨论】:

    标签: c# asp.net asp.net-mvc entity-framework owin


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2015-08-21
      • 1970-01-01
      • 1970-01-01
      • 2014-01-18
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 2012-03-21
      相关资源
      最近更新 更多