2017-05-05 39 views
2

我正在構建應用程序,將所有業務邏輯與控制器分離以分離庫。我想從控制器中訪問ApplicationUserManager,並且沒有Request/OwinContext那裏。 可能嗎?如果是的話,使用DI容器註冊ApplicationUserManager的更好方法是什麼? (Autofac,ninject,等等)ApplicationUserManager超出控制器

+0

那怎麼我所做的DI註冊http://tech.trailmax.info/2014/09/aspnet-identity-and-ioc-container-registration/ – trailmax

回答

0

如果你想分開你的業務邏輯,那麼你可以使用UserStoreUserManager。而我永遠愛unity依賴注入。

例子:

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