How to move MVC 5 IdentityModels.cs into a separat

2019-04-07 17:46发布

问题:

I wonder if someone ran into the issue that I am having with trying to move ApplicationUser into Models project (where all other models reside including the ones related to Users table).

My test MVC 5 solution consists of a web project and two class libraries: one for data access layer (DAL) and the other for Models. I references AspNet.Identity.EntityFramework in all three projects. In my DAL class I implement Repository pattern and a UnitOfWork. UnitOfWork extends IdentityDbContext<ApplicationUser>. ApplicationUser : IdentityUser is in Models class library.

In my web project UnitOfWork is instantiated using Autofac DI. For regular controllers I defined a base class that inherits from Controller and takes IUnitOfWork as a parameter in the constructor. All controllers inherit from my custom base controller. I ran into a problem with AccountController. It has two constructors: one with no parameters that seems to instantiate ApplicationDbContext, the other takes UserManager as a parameter.

The parameter-less constructor gives me most of the grief. I tried many things: make accountcontroller inherit from my custom base controller, then try to inherit it from the Controller class. At best I succeed in making my solution compile but when I test the app and fill out user Registration form I get 'Object is not instantiated' message. When I debug I see that the second constructor in AccountController gets called but UserManager is null there.

Any ideas? I would really appreciate somebody's brainy input into this.

回答1:

Take a look at the SimpleSecurity Project. This project decouples ASP.NET Identity from the web application and puts ApplicationUser into an assembly separate from the web application. This project also has a version that uses SimpleMembership. For ASP.NET Identity look in the AspNetIdentity folder. The assembly for the security functions is in AspNetIdentity/SimpleSecurity.AspNetIdentity and the reference web application is in AspNetIdentity/SimpleSecurity.AspNetIdentity/RefApp.