0

有谁知道我们如何在.net core 2.0 的运行时将上下文注入用户管理器> MongoDB serStore。

由于上下文是动态的,我们无法在启动时执行此操作,但无法访问 UserStore 并且 UserManager 有太多变量需要新建,这是错误的。有什么解决办法吗?

public class UserStore<TUser> :
        IUserPasswordStore<TUser>,
        IUserRoleStore<TUser>,
        IUserLoginStore<TUser>,
        IUserSecurityStampStore<TUser>,
        IUserEmailStore<TUser>,
        IUserClaimStore<TUser>,
        IUserPhoneNumberStore<TUser>,
        IUserTwoFactorStore<TUser>,
        IUserLockoutStore<TUser>,
        IQueryableUserStore<TUser>,
        IUserAuthenticationTokenStore<TUser>
    where TUser : IdentityUser
{
    private readonly IMongoCollection<TUser> _Users;

//这是我们要在运行时注入用户的地方

    public UserStore(IMongoCollection<TUser> users)
    {
        _Users = users;
    }

    public virtual void Dispose()
    {
        // no need to dispose of anything, mongodb handles connection pooling automatically
    }

    public virtual async Task<IdentityResult> CreateAsync(TUser user, CancellationToken token)
    {
        await _Users.InsertOneAsync(user, cancellationToken: token);
        return IdentityResult.Success;
    }

不幸的是,用户在启动时为空,应该是因为那时尚未创建租户。

我们也一直在使用 saaskit.Multitenancy,但找不到解决方案。

任何帮助将非常感激。

谢谢

4

1 回答 1

0

我认为您需要一个通用存储库来充当 IMongoCollection 的包装器,然后将存储库注入控制器中

 public class Repository<T>
{
    public IMongoCollection<T> Collection { get; private set; }

    public Repository(IDbFactory dbFactory)
    {
        MongoClient client = new MongoClient("ur connection string");

        this.Collection = client.GetDatabase("db").GetCollection<T>(typeof(T).Name);
    }



       public T Find(Expression<Func<T, bool>> filter)
    {
        return this.Collection.AsQueryable<T>().FirstOrDefault<T>(filter);
    }

    public async Task<T> FindAsync(Expression<Func<T, bool>> filter)
    {
        return await this.Collection.AsQueryable<T>().FirstOrDefaultAsync<T>(filter);
    }

            // here add more methods
}

然后在 Startup.cs 中注册如下依赖项

 public void ConfigureServices(IServiceCollection services)
    {          
        services.AddTransient(typeof(IRepository<>), typeof(Repository<>));

        services.AddMvc();
    }

最后在控制器内部你注入通用存储库,也不要忘记在通用存储库中实现 IDisopsible

 public class ProductController : Controller
{
    private readonly IRepository<Product> _productRepository = null;

    public ProductController(IRepository<Product> productRepository)
    {
        this._productRepository = productRepository;
    }
}
于 2018-03-07T10:30:13.080 回答