使用Microsoft.AspNetCore.Identity.MongoDB进行多租户。我们如何将动态租户注入MongoDbContext

时间:2018-02-09 14:16:12

标签: mongodb asp.net-core-2.0 usermanager

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

由于上下文是动态的,但我们无法在启动时执行此操作,但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;

//这就是我们想要在RUNTIME注入用户的地方

    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而无法找到解决方案。

非常感谢任何帮助。

由于

1 个答案:

答案 0 :(得分: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();
    }

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

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

    public ProductController(IRepository<Product> productRepository)
    {
        this._productRepository = productRepository;
    }
}