如何将对象注入到静态方法中?

问题描述 投票:0回答:1

我有一个 .net core 5 应用程序,它有一个

appsettings.json
文件,其中我列出了数据库的连接字符串。

我定义了一个

Database
类,负责分发
IDbConnection
对象。

public class Database
{
    public Database(IConfiguration config) // config is injected 
    {
        Db1ConnectionString = config.GetConnectionString("db1");
        Db2ConnectionString = config.GetConnectionString("db2");
    }

    public IDbConnection GetConnection() 
    {
        // do some logic to decide, either Db1 or Db2 to use
        return new SQLiteConnection(SelectedDbConnectionString);
    }
}

然后我将这个

Database
注入到
Startup.cs

services.AddScoped<IDatabase, Database>();    // IDatabase is interface of Database

假设我有一堂课

Person

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

我正在使用 Dapper 来获取

IEnumerable<Person>
。我正在编写逻辑来获取同一类本身中的对象集合。含义:Person 类知道如何获取其自身的集合。
Animal
类有自己的获取自身集合的逻辑。

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public static IEnumerable<Person> GetAll()
    {
         string sql = "select id, name from person where ...... ";
         using var con = Database.GetConnection();   // this does not work
                 // because the GetConnection() is not static.
         return con.Query<Person>(sql);
    }

}

上面的代码将不起作用,因为我需要在静态方法中使用

Database
的实例。我想在
Database
构造函数中注入
Person
,但这会给 Dapper 带来困难。所以我想我需要为
Person
编写一个空的构造函数。但是,另一个构造函数(接受
IDatabase
)无法保留该数据库对象的引用,直到静态方法需要它为止。

我想过将

Database
转换为静态类,或者将
GetConnection()
更改为静态方法,但是这样我将无法将其注入到
Startup.cs
中。

我不想硬核连接字符串,因为它们可能会在运行时发生变化。

我觉得这个问题有一个直接的解决方案,而且也一定是显而易见的。

c# dependency-injection dapper
1个回答
0
投票

请问,为什么需要自己获取Person数据?只是我认为创建像 PersonData(或类似的东西)这样的新服务可能会更简单。并在那里提供您的数据库实例,因此您可以获取数据。只是我无法想象你必须这样做的情况)

© www.soinside.com 2019 - 2024. All rights reserved.