asp.net-core – 在运行时更改注入的对象

前端之家收集整理的这篇文章主要介绍了asp.net-core – 在运行时更改注入的对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想拥有IUserRepository的多个实现,每个实现都可以使用MongoDB或任何sql数据库数据库类型.为此,我有ITenant接口,它具有连接字符串和其他租户配置.租户已被注入IUserRepository MongoDB或任何sqlDB实现.我需要知道的是如何正确地更改注入的存储库以选择租户的数据库.

接口

public interface IUserRepository 
{
    string Login(string username,string password);
    string logoff(Guid id);
}

public class User
{
    public Guid Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }

}

public interface ITenant
{
    string CompanyName { get; }
    string ConnectionString { get; }
    string DataBaseName { get; }
    string EncriptionKey { get; }

}

重要的是要知道租户ID已通过标头请求传递给API

StartUp.cs

// set inject httpcontet to the tenant implemantion
services.AddTransient<IHttpContextAccessor,HttpContextAccessor>();

// inject tenant
services.AddTransient<ITenant,Tenant>();

// inject mongo repository but I want this to be programmatically
services.AddTransient<IUserRepository,UserMongoRepository>();

示例Mongo实现

public class UserMongoRepository : IUserRepository
{

    protected ITenant Tenant 

    public UserMongoRepository(ITenant tenant) :
        base(tenant)
    {
        this.Tenant = tenant;
    }

    public string Login(string username,string password)
    {

        var query = new QueryBuilder<User>().Where(x => x.Username == username);
        var client = new MongoClient(this.Tenant.ConnectionString);var server = client.GetServer();
        var database =  client.GetServer().GetDatabase(this.Tenant.DataBaseName);
        var user = database.GetCollection<User>.FindAs<User>(query).AsQueryable().FirstOrDefault();

        if (user == null)
            throw new Exception("invalid username or password");

        if (user.Password != password)
            throw new Exception("invalid username or password");

         return "Sample Token";

    }

    public string logoff(Guid id)
    {

        throw new NotImplementedException();
    }

}

承租人

public class Tenant : ITenant
{

    protected IHttpContextAccessor Accesor;
    protected IConfiguration Configuration;

    public Tenant(IHttpContextAccessor accesor,IDBConfiguration config)
    {
        this.Accesor = accesor;
        this.Configuration = new Configuration().AddEnvironmentVariables();
        if (!config.IsConfigure)
            config.ConfigureDataBase();
    }


    private string _CompanyName;
    public string CompanyName
    {
        get
        {
            if (string.IsNullOrWhiteSpace(_CompanyName))
            {
                _CompanyName = this.Accesor.Value.Request.Headers["Company"];
                if (string.IsNullOrWhiteSpace(_CompanyName))
                    throw new Exception("Invalid Company");
            }
            return _CompanyName;
        }
    }

    private string _ConnectionString;
    public string ConnectionString
    {
        get
        {
            if (string.IsNullOrWhiteSpace(_ConnectionString))
            {
                _ConnectionString = this.Configuration.Get(this.CompanyName + "_" + "ConnectionString");
                if (string.IsNullOrWhiteSpace(_ConnectionString))
                    throw new Exception("Invalid ConnectionString Setup");
            }
            return _ConnectionString;
        }
    }

    private string _EncriptionKey;
    public string EncriptionKey
    {
        get
        {
            if (string.IsNullOrWhiteSpace(_EncriptionKey))
            {
                _EncriptionKey = this.Configuration.Get(this.CompanyName + "_" + "EncriptionKey");
                if (string.IsNullOrWhiteSpace(_EncriptionKey))
                    throw new Exception("Invalid Company Setup");
            }
            return _EncriptionKey;
        }
    }

    private string _DataBaseName;
    public string DataBaseName
    {
        get
        {
            if (string.IsNullOrWhiteSpace(_DataBaseName))
            {
                _DataBaseName = this.Configuration.Get(this.CompanyName + "_" + "DataBaseName");
                if (string.IsNullOrWhiteSpace(_DataBaseName))
                    throw new Exception("Invalid Company Setup");
            }
            return _DataBaseName;
        }
    }
}

调节器

public class UsersController : Controller
{
    protected IUserRepository DataService;

    public UsersController(IUserRepository dataService)
    {
        this.DataService = dataService;
    }

    // the controller implematation

}

解决方法

您可以尝试注入工厂而不是实际的存储库.工厂将负责根据当前用户身份构建正确的存储库.

它可能需要更多的锅炉板代码,但它可以实现你想要的.一点点继承甚至可能使控制器代码更简单.

原文链接:https://www.f2er.com/aspnet/251427.html

猜你在找的asp.Net相关文章