Can OWIN replace DI in a ASP.NET MVC application?

2019-04-10 13:13发布

问题:

About a year ago, the automatically generated MVC project upon creation in Visual Studio included nothing about OWIN. As someone who is making an application again, trying to understand the changes, I'd like to know if OWIN can replace my DI.

From what I understand, this following bit from Startup.Auth.cs is what centralizes the creation of the user manager (to handle identities), as well as the creation of the database connection for the application.

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...
    }
 }

From a very helpful source: http://blogs.msdn.com/b/webdev/archive/2014/02/12/per-request-lifetime-management-for-usermanager-class-in-asp-net-identity.aspx, it appears as if we can access the user manager or dbcontext at any time with code like the following

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...
}

If I understand everything correctly, all that I can do to transfer from using StructureMap to OWIN (to handle the DI) is simply structure my controllers like the AccountController from above. Is there anything I'm missing or do I still need DI in my application/does OWIN give me DI?

回答1:

I personally don't like the idea of using OWIN to resolve dependencies.

The default implementation of AccountController.UserManager (as well as some other AccountManager properties) demonstrates an example of service locator as an anti-pattern. So I prefer to remove all that stuff and follow DI principles. This blog post shows how the default project template could be refactored to follow these principles.

I hope that dependency injection will be improved in the next versions of ASP.NET. They actually promised support of dependency injection out of the box.