Tim
Tim

Reputation: 307

ApplicationUserManager out of Controller

I'm building the application where all business logic is separated from controller to separate lib. I want to access ApplicationUserManager out of controller and without having the Request/OwinContext there. Is It possible? And if yes what would be the better way to register ApplicationUserManager using DI container? (Autofac, ninject, whatever)

Upvotes: 2

Views: 449

Answers (1)

Ashiquzzaman
Ashiquzzaman

Reputation: 5284

If you want to separate your business logic then you can use UserStore and UserManager.And I always love unity dependency injection.

Example:

 public class UserRepository
{
    private readonly UserStore _store;
    private readonly UserManager _manager;

    public UserRepository(DbContext context)
    {
        _store = new UserStore<ApplicationUser>(context);
        _manager = new UserManager<ApplicationUser>(_store);

    }

    public async Task<ApplicationUser> GetUserByNameAsync(string username)
    {
        return await _store.FindByNameAsync(username);
    }

    public async Task<IEnumerable<ApplicationUser>> GetAllUsersAsync()
    {
        return await _store.Users.ToArrayAsync();

    }
    public async Task CreateAsync(ApplicationUser user, string password)
    {
        await _manager.CreateAsync(user, password);
    }

    public async Task DeleteAsync(ApplicationUser user)
    {
        await _manager.DeleteAsync(user);
    }

    public async Task UpdateAsync(ApplicationUser user)
    {
        await _manager.UpdateAsync(user);
    }

    private bool _disposed = false;
    public void Dispose()
    {
        if (!_disposed)
        {
            _manager.Dispose();
            _store.Dispose();
        }

        _disposed = true;
    }
}

Upvotes: 1

Related Questions