Some services are not able to be constructed Error while validating the service descriptor Lifetime: Scoped Unable to resolve service for type - asp.net-mvc

my usermanager services is :
public class UserManagerService : IUserManagerService
{
private readonly UserManager<UserModel> userManager;
private readonly UserServiceHelper userServiceHelper;
public UserManagerService(UserManager<UserModel> _userManager)
{
this.userManager = _userManager;
userServiceHelper = new UserServiceHelper();
}
public async Task<bool> CreateUser(UserViewModel user)
{
try
{
var new_user = userServiceHelper.GetNewItems(user);
await userManager.CreateAsync(new_user);
return true;
}
catch(Exception e)
{
throw;
}
}
IUsermanagerServices interface is :
public interface IUsermanagerServices
{
Task<bool> CreateUser(UserViewModel user);
Task<bool> CreateUserBatch(List<UserViewModel> users);
Task<bool> DeleteUser(UserViewModel user);
}
And userapicontroller is :
[Route("api/[controller]")]
[ApiController]
public class UserApiController : ControllerBase
{
private readonly IUserManagerService userManager;
public UserApiController(IUserManagerService _userManager)
{
userManager = _userManager;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] List<UserViewModel> users)
{
try
{
var _result = await userManager.CreateUserBatch(users);
var _response = new ResponseModel<bool>()
{
Content = _result,
Message = "np"
};
return Ok(_response);
}
catch(Exception e)
{
var _response = new ResponseModel<bool>()
{
Content = false,
ExceptionMessage = e.Message,
HasError = true
}.ToString();
return Problem(_response);
}
}
service extension is :
public static void AddUserManagerServices(this IServiceCollection services)
{
services.AddScoped<IUserManagerService, UserManagerService>();
}
and program :
#region
builder.Services.AddUserManagerServices();
#endregion
var app = builder.Build();
in this last line i have exception
Some services are not able to be constructed (Error while validating the service
descriptor 'ServiceType: Lifetime: Scoped ImplementationType:
Unable to resolve service for type while attempting to activate)
how can i fix it ?

Related

How to seed the Authentication db in ASP NET MVC

In which module do I do the seeding of the db? I want to add roles and users if they do not exist yet.
In NET Core I would use the startup file in this way:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
using (IServiceScope serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
var roleManager = serviceScope.ServiceProvider.GetService<RoleManager<IdentityRole>>();
var userManager = serviceScope.ServiceProvider.GetService<UserManager<User>>();
DbSeeder.Seed(Configuration, dbContext, roleManager, userManager);
}
}
and in my class DBSeeder:
public static class DbSeeder
{
public static void Seed(IConfiguration configuration,
ApplicationDbContext dbContext,
RoleManager<IdentityRole> roleManager,
UserManager<User> userManager)
{
if (!dbContext.Users.Any()) CreateUsers(configuration, dbContext, roleManager, userManager).GetAwaiter().GetResult();
}
private static async Task CreateUsers(IConfiguration configuration,
ApplicationDbContext dbContext,
RoleManager<IdentityRole> roleManager,
UserManager<User> userManager)
{
string role_Administrator = "Administrator";
string role_RegisteredUser = "RegisteredUser";
if (!await roleManager.RoleExistsAsync(role_Administrator))
{
await roleManager.CreateAsync(new IdentityRole(role_Administrator));
}
if (!await roleManager.RoleExistsAsync(role_RegisteredUser))
{
await roleManager.CreateAsync(new IdentityRole(role_RegisteredUser));
}
var user_Admin = new User()
{
SecurityStamp = Guid.NewGuid().ToString(),
UserName = "Admin",
Email = configuration["ContactUs"],
DisplayName = "Admin",
EmailConfirmed = true
};
if (await userManager.FindByNameAsync(user_Admin.UserName) == null)
{
await userManager.CreateAsync(user_Admin, "Pass4Admin");
await userManager.AddToRoleAsync(user_Admin, role_RegisteredUser);
await userManager.AddToRoleAsync(user_Admin, role_Administrator);
}
await dbContext.SaveChangesAsync();
}

Webapi Response 500 Internal Server Error

I made an asp.net core web api and implemented some logic to register user.
But the issue is that whenever I call the controller from postman, it gives me 500 Internal Server Error.I also implemented an simple IActionResult to return welcome message, that also don't work. Here is my code.
[ApiController]
[Route("api/[controller]")]
public class AuthController : Controller
{
private readonly IAuthRepository _repo;
public AuthController(IAuthRepository repo)
{
_repo = repo;
}
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody]CreateUserDTO createUserDto)
{
createUserDto.Username=createUserDto.Username.ToLower();
if(await _repo.UserExists(createUserDto.Username))
return BadRequest("User With This User Name Already Exists");
var userToCreate=new User
{
UserName=createUserDto.Username
};
var createdUser=await _repo.Register(userToCreate,createUserDto.Password);
return Ok("user registered");
}
[HttpGet]
public IActionResult Get()
{
var message="welcome message";
return Ok(message);
}
}
Looking to hear from you soon.
Thanks
I figured out the problem.
The problem was with my AuthRepository constructor where I wasn't specifying the public modifier.
Here is my AuthRepository code (working)
public class AuthRepository : IAuthRepository
{
private readonly ApplicationDatabase _db;
public AuthRepository(ApplicationDatabase db)
{
_db = db;
}
public async Task<User> Login(string username, string password)
{
var user=await _db.Users.Where(x=>x.UserName==username).FirstOrDefaultAsync();
if (user==null)
return null;
if(!verifyPasswordHash(password,user.PasswordHash,user.PasswordSalt))
return null;
return user;
}
private bool verifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
{
using(var hmac=new System.Security.Cryptography.HMACSHA512(passwordSalt))
{
var computedPasswordHash=hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
for (int i = 0; i < computedPasswordHash.Length; i++)
{
if (computedPasswordHash[i]!=passwordHash[i])
{
return false;
}
}
}
return true;
}
public async Task<User> Register(User user, string password)
{
byte[] passwordHash,passwordSalt;
CreatePasswordHashSalt(password,out passwordHash,out passwordSalt);
user.PasswordHash=passwordHash;
user.PasswordSalt=passwordSalt;
await _db.Users.AddAsync(user);
_db.SaveChangesAsync();
return user;
}
private void CreatePasswordHashSalt(string password, out byte[] passwordHash, out byte[] passwordSalt)
{
using(var hmac=new System.Security.Cryptography.HMACSHA512())
{
passwordSalt=hmac.Key;
passwordHash=hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
}
}
public async Task<bool> UserExists(string username)
{
if(await _db.Users.AnyAsync(x=>x.UserName==username))
return true;
return false;
}
}

Inject into the Startup class

Is it possible to use an IOC framework like Castle Windsor to inject into the Startup method. I mean something like this:
public class Startup()
{
IMyObject MyObject = new MyObject();
public Startup(MyObject myObject)
{
MyObject = myObject();
}
}
I am trying to drop and create a database on startup using NHibernate. Alternatively is there a "better" place to drop and create the database using NHibernate?
I do something like this for integration tests using specflow.
I have a NHibernateInitializer class that I inherit in all my projects that looks like this
public abstract class NHibernateInitializer : IDomainMapper
{
protected Configuration Configure;
private ISessionFactory _sessionFactory;
private readonly ModelMapper _mapper = new ModelMapper();
private Assembly _mappingAssembly;
private readonly String _mappingAssemblyName;
private readonly String _connectionString;
protected NHibernateInitializer(String connectionString, String mappingAssemblyName)
{
if (String.IsNullOrWhiteSpace(connectionString))
throw new ArgumentNullException("connectionString", "connectionString is empty.");
if (String.IsNullOrWhiteSpace(mappingAssemblyName))
throw new ArgumentNullException("mappingAssemblyName", "mappingAssemblyName is empty.");
_mappingAssemblyName = mappingAssemblyName;
_connectionString = connectionString;
}
public ISessionFactory SessionFactory
{
get
{
return _sessionFactory ?? (_sessionFactory = Configure.BuildSessionFactory());
}
}
private Assembly MappingAssembly
{
get
{
return _mappingAssembly ?? (_mappingAssembly = Assembly.Load(_mappingAssemblyName));
}
}
public void Initialize()
{
Configure = new Configuration();
Configure.EventListeners.PreInsertEventListeners = new IPreInsertEventListener[] { new EventListener() };
Configure.EventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[] { new EventListener() };
Configure.SessionFactoryName(System.Configuration.ConfigurationManager.AppSettings["SessionFactoryName"]);
Configure.DataBaseIntegration(db =>
{
db.Dialect<MsSql2008Dialect>();
db.Driver<SqlClientDriver>();
db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
db.IsolationLevel = IsolationLevel.ReadCommitted;
db.ConnectionString = _connectionString;
db.BatchSize = 20;
db.Timeout = 10;
db.HqlToSqlSubstitutions = "true 1, false 0, yes 'Y', no 'N'";
});
Configure.SessionFactory().GenerateStatistics();
Map();
}
public virtual void InitializeAudit()
{
var enversConf = new Envers.Configuration.Fluent.FluentConfiguration();
enversConf.Audit(GetDomainEntities());
Configure.IntegrateWithEnvers(enversConf);
}
public void CreateSchema()
{
new SchemaExport(Configure).Create(false, true);
}
public void DropSchema()
{
new SchemaExport(Configure).Drop(false, true);
}
private void Map()
{
_mapper.AddMappings(MappingAssembly.GetExportedTypes());
Configure.AddDeserializedMapping(_mapper.CompileMappingForAllExplicitlyAddedEntities(), "MyWholeDomain");
}
public HbmMapping HbmMapping
{
get { return _mapper.CompileMappingFor(MappingAssembly.GetExportedTypes()); }
}
public IList<HbmMapping> HbmMappings
{
get { return _mapper.CompileMappingForEach(MappingAssembly.GetExportedTypes()).ToList(); }
}
/// <summary>
/// Gets the domain entities.
/// </summary>
/// <returns></returns>
/// <remarks>by default anything that derives from EntityBase and isn't abstract or generic</remarks>
protected virtual IEnumerable<System.Type> GetDomainEntities()
{
List<System.Type> domainEntities = (from t in MappingAssembly.GetExportedTypes()
where typeof(EntityBase<Guid>).IsAssignableFrom(t)
&& (!t.IsGenericType || !t.IsAbstract)
select t
).ToList();
return domainEntities;
}
}
Then in my global.asax Application_Begin event handler I configure it
public class MvcApplication : HttpApplication
{
private const String Sessionkey = "current.session";
private static IWindsorContainer Container { get; set; }
private static ISessionFactory SessionFactory { get; set; }
public static ISession CurrentSession
{
get { return (ISession) HttpContext.Current.Items[Sessionkey]; }
private set { HttpContext.Current.Items[Sessionkey] = value; }
}
protected void Application_Start()
{
Version version = Assembly.GetExecutingAssembly().GetName().Version;
Application["Version"] = String.Format("{0}.{1}", version.Major, version.Minor);
Application["Name"] = ConfigurationManager.AppSettings["ApplicationName"];
//create empty container
//scan this assembly for any installers to register services/components with Windsor
Container = new WindsorContainer().Install(FromAssembly.This());
//API controllers use the dependency resolver and need to be initialized differently than the mvc controllers
GlobalConfiguration.Configuration.DependencyResolver = new WindsorDependencyResolver(Container.Kernel);
//tell ASP.NET to get its controllers from Castle
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(Container.Kernel));
//initialize NHibernate
ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings[Environment.MachineName];
if (connectionString == null)
throw new ConfigurationErrorsException(String.Format("Connection string {0} is empty.",
Environment.MachineName));
if (String.IsNullOrWhiteSpace(connectionString.ConnectionString))
throw new ConfigurationErrorsException(String.Format("Connection string {0} is empty.",
Environment.MachineName));
string mappingAssemblyName = ConfigurationManager.AppSettings["NHibernate.Mapping.Assembly"];
if (String.IsNullOrWhiteSpace(mappingAssemblyName))
throw new ConfigurationErrorsException(
"NHibernate.Mapping.Assembly key not set in application config file.");
var nh = new NHInit(connectionString.ConnectionString, mappingAssemblyName);
nh.Initialize();
nh.InitializeAudit();
SessionFactory = nh.SessionFactory;
AutoMapConfig.RegisterMaps();
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ModelBinderConfig.RegisterModelBinders(ModelBinders.Binders);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}
protected void Application_OnEnd()
{
//dispose Castle container and all the stuff it contains
Container.Dispose();
}
protected void Application_BeginRequest() { CurrentSession = SessionFactory.OpenSession(); }
protected void Application_EndRequest()
{
if (CurrentSession != null)
CurrentSession.Dispose();
}
}
}

Cannot create instance of repository object in action filter MVC

public interface IUserRepository : IBaseRepository<user>
{
user GetUser(int userId);
user Get(string Email);
}
public class UserRepository : BaseRepository<user>, IUserRepository
{
public UserRepository(IUnitOfWork unit) : base(unit)
{
}
public void Dispose()
{
throw new NotImplementedException();
}
public user GetUser(int userId)
{
return dbSet.Where(x => x.ID == userId).FirstOrDefault();
}
public user Get(string Email)
{
var obj = dbSet.Where(s => s.Email == Email).FirstOrDefault();
return obj;
}
}
And I am using the repository in my controller as below
public class AccountController : Controller
{
private readonly ApplicationUserManager UserManager;
private readonly ApplicationSignInManager SignInManager;
private readonly IAuthenticationManager AuthenticationManager;
private readonly IUnitOfWork uow;
private readonly UserRepository userrepo;
public AccountController(UserRepository _userrepo, ApplicationUserManager userManager, ApplicationSignInManager signInManager, IAuthenticationManager authenticationManager,IUnitOfWork _uow)
{
this.UserManager = userManager;
this.SignInManager = signInManager;
this.AuthenticationManager = authenticationManager;
this.uow = _uow;
userrepo = _userrepo;
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid )
{
var user = UserManager.FindByEmail(model.Email);
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
if (result)
{
var myUser = userRepo.Get(user.Id);
if (myUser.SubscriptionStatus == 1)
{
return RedirectToAction("ChangePassword", "Manage", new { ReturnUrl = returnUrl });
}
else
{
return RedirectToAction("Index","Admin");
}
}
}
}
And this is my action filter
public class CheckFirstLoginAttribute : ActionFilterAttribute
{
private readonly ApplicationUserManager UserManager;
private readonly IUnitOfWork uow;
private readonly UserRepository userrepo;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
string uName = HttpContext.Current.User.Identity.Name;
if (!string.IsNullOrEmpty(uName))
{
//var user = UserManager.FindByEmailAsync(uName);
//The above & below lines are not creating instance of the UserManager & UserRepository object, it is always null
user cUser= userrepo.GetUserId(uName);
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "Manage",
action = "ChangePassword"
}));
}
}
}
And I am using Unity for the dependency injection
public class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
#endregion
private static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<MyDbContext>();
container.RegisterType<UserRepository>();
container.RegisterType<IUnitOfWork, UnitOfWork>();
container.RegisterType<ApplicationDbContext>();
container.RegisterType<ApplicationSignInManager>();
container.RegisterType<ApplicationUserManager>();
container.RegisterType<HomeController>();
container.RegisterType<AccessCodeController>();
container.RegisterType<AdminController>();
container.RegisterType<IAuthenticationManager>(
new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
container.RegisterType<IUserStore<MyUser, int>, UserStore<MyUser, MyRole, int, MyUserLogin, MyUserRole, MyUserClaim>>(
new InjectionConstructor(typeof(ApplicationDbContext)));
}
}
How can I create the instance of the repository class and access the Get(string email) method. So that I can check the subscription status from the database.
I tried many ways and always failed to create the instance.
Kindly Help me.
Thanks
Tarak
public class CheckFirstLoginAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
string uName = HttpContext.Current.User.Identity.Name;
if (!string.IsNullOrEmpty(uName))
{
//Here is how I could get the instance of the repository
//I had to register the repository type and then
//I resolved it to obtain the object of the repository and
//access the methods in the repository
var container = new UnityContainer();
container.RegisterType<IUnitOfWork, UnitOfWork>();
container.RegisterType<UserRepository>();
UserRepository repo = container.Resolve<UserRepository>();
user cUser = repo.GetUserId(uName);
if (cUser.SubscriptionStatus == 1)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "Manage",
action = "ChangePassword"
}));
}
}
}
}

Trying to register a user from another controller other than AccountController gives an error

Totally messed up my last question so posting a new one.
MyTestController:
[HttpPost]
public async Task<ActionResult> Index(MyTestViewModel viewModel)
{
if (ModelState.IsValid)
{
AccountController ac = new AccountController();
var user = new ApplicationUser()
{
UserName = viewModel.Email
};
var result = await ac.UserManager.CreateAsync(user, viewModel.Password);
if (result.Succeeded)
{
await ac.SignInAsync(user, isPersistent: true);
}
else
{
ac.AddErrors(result);
}
The SignInAsync method in AccountController (changed this from private to public):
public async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
While trying to register the user it gives me the following error:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 411: get
Line 412: {
Line 413: return HttpContext.GetOwinContext().Authentication;
Line 414: }
Line 415: }
Those lines in AccountController:
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
Everything in the AccountController is default MVC 5 app stuff.
It is not possible to call these methods from another controller, like in my example above?
And why am I getting a NullReferenceException on line 413?
Calling a Controller method from another Controller is difficult because of properties like the HttpContext which need to be properly initialized. This is usually done by the MVC framework which creates the controller using a ControllerFactory and at some point during this process the protected method Initialize is called on the controller which ensures that the HttpContext property is set.
This is why you get the exception on line 413, because the Initialize method hasn't been called on the controller you created using the new operator.
I think it would be easier to refactor out the functionality you want to share.
E.g. if both AccountController and your MyTestController holds a reference to something like this
public class AccountManager
{
public UserManager<ApplicationUser> UserManager { get; private set; }
public HttpContextBase HttpContext { get; private set; }
public AccountManager()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public AccountManager(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
public void Initialize(HttpContextBase context)
{
HttpContext = context;
}
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
public async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
}
You would then modify the AccountController like this:
public class AccountController : Controller
{
public AccountController()
: this(new AccountManager())
{
}
public AccountController(AccountManager accountManager)
{
AccountManager = accountManager;
}
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
AccountManager.Initialize(this.HttpContext);
}
public UserManager<ApplicationUser> UserManager
{
get
{
return AccountManager.UserManager;
}
}
public AccountManager AccountManager { get; private set; }
And your MyTestController would be like this:
public class MyTestController : Controller
{
public MyTestController ()
: this(new AccountManager())
{
}
public MyTestController (AccountManager accountManager)
{
AccountManager = accountManager;
}
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
AccountManager.Initialize(this.HttpContext);
}
public AccountManager AccountManager { get; private set; }
[HttpPost]
public async Task<ActionResult> Index(MyTestViewModel viewModel)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser()
{
UserName = viewModel.Email
};
var result = await AccountManager.UserManager.CreateAsync(user, viewModel.Password);
if (result.Succeeded)
{
await AccountManager.SignInAsync(user, isPersistent: true);
}
else
{
AddErrors(result); //don't want to share this a it updates ModelState which belongs to the controller.
}
Update:
Had to make som minor changes:
I had to change the UserManager property since the Dispose method uses the setter method:
private UserManager<ApplicationUser> _userManager;
public UserManager<ApplicationUser> UserManager
{
get { return AccountManager.UserManager; }
private set { _userManager = value; }
}
protected override void Dispose(bool disposing)
{
if (disposing && UserManager != null)
{
UserManager.Dispose();
UserManager = null;
}
base.Dispose(disposing);
}
I had to add the AddErrors method to MyTestController (as you pointed out that we don't want to share that method):
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
I re-added this line to the AccountManager property in the AccountManager class (not really related to the question but I had it in my project)
UserManager.UserValidator = new UserValidator(UserManager) { AllowOnlyAlphanumericUserNames = false };
For me it working like a charm after setting the current ControllerContext to AccountControllerContext. Not sure if there are any drawbacks with this approach.
//This is employee controller class
public ActionResult Create([Bind(Include = "EmployeeId,FirstName,LastName,DOJ,DOB,Address,City,State,Mobile,Landline,ReportsTo,Salary")] Employee employee)
{
if (ModelState.IsValid)
{
AccountController accountController = new AccountController();
accountController.ControllerContext = this.ControllerContext;
//accountController.UserManager;
var userId = accountController.RegisterAccount(new RegisterViewModel { Email = "temp#temp.com", Password = "Pravallika!23" });
if (!string.IsNullOrEmpty(userId))
{
employee.UserId = userId;
employee.CreatedBy = User.Identity.GetUserId();
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
}
//customized method in AccountController
public string RegisterAccount(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = UserManager.Create(user, model.Password);
//to add roles
//UserManager.AddToRole(user.Id, "Admin");
if (result.Succeeded)
{
return user.Id;
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed
return null;
}

Resources