Issues Configuring StructureMap.MVC5 to work with Identity

空扰寡人 提交于 2019-12-03 17:06:09
EF0

As @Erik Funkenbusch pointed out, I was doing competing things. I ended up making UserManager an auto-property, removed the parameterless constructor, and let StructureMap inject the ApplicationUserManager.

    public ApplicationUserManager UserManager { get; private set; }

    public AccountController(ApplicationUserManager userManager)
    {
        UserManager = userManager;
    }

Then, I simply needed to configure the IUserStore and DbContext that Identity uses in DefaultRegistry.cs:

        For<IUserStore<ApplicationUser, int>>()
            .Use<UserStore<ApplicationUser, CustomRole, int, CustomUserLogin, 
                            CustomUserRole, CustomUserClaim>>()
            .LifecycleIs<HttpContextLifecycle>();

        For<DbContext>()
            .Use(() => new ApplicationDbContext())
            .LifecycleIs<HttpContextLifecycle>();  


This was all I needed to do to get StructureMap.MVC working with Identity.

Part of my initial hangup was that I didn't realize the way StructureMap.MVC (and other DI containers) worked. (See my related question.) I was expecting it to just work with my stock AccountController which got initialized by the framework (and thought it magically intercepted object creation to inject anything I had configured), not realizing that StructureMap must initialize the controllers itself in order for it to perform constructor injection. So when I ran into issues, I was A. Surprised that StructureMap had anything to do with my AccountController in the first place (since I wasn't explicitly configuring injection for any of its parameters - only for my Repository used in other controllers), and B. I wasn't thinking about changing my stock code but rather thinking about how to configure StructureMap. It turned out I needed to do both. Luckily, it was an easy modification and I learned a little more about how DI containers work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!