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

Zac*_*Zac 4 c# asp.net asp.net-mvc entity-framework owin

大约一年前,在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...
    }
 }
Run Code Online (Sandbox Code Playgroud)

从一个非常有用的来源: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...
}
Run Code Online (Sandbox Code Playgroud)

如果我理解了所有内容,我可以做的就是从使用StructureMap转移到OWIN(处理DI)只是构造我的控制器,如上面的AccountController.有什么我缺少或做的我仍然需要DI在我的应用程序/ OWIN给我DI吗?

Ser*_*diy 6

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

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

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