c# - .Net core将SqlConnection注入(inject)到服务中

标签 c# asp.net-core

我正在尝试使用 sql server 编写一个非常简单的 CRUD api,但不使用 EF

我的数据类看起来像这样

public class DataClass : ICommanderRepo
{
    protected string _connectionString { get; set; }
    public DataClass(string connectionString)
    {
        _connectionString = connectionString;
    }
    public IEnumerable<Command> GetAppCommands()
    {
        var commands = new List<Command>();
        using (SqlConnection con = new SqlConnection(_connectionString))
        {
            using(SqlCommand cmd = new SqlCommand("spR_GetAllCommands",con))
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                if(reader.HasRows)
                {
                    while(reader.Read())
                    {
                        commands.Add(
                            new Command { Id = Convert.ToInt32(reader[0].ToString()), HowTo = reader[1].ToString(), Line = reader[2].ToString(), Platform = reader[3].ToString() }
                            );
                    }
                }
            }
        }
        return commands;
    }
 }

我认为效果很好。但是,当我在startup.cs中设置服务时,我做错了一些事情

services.AddTransient<ICommanderRepo, DataClass>(
        opt => opt.UseSqlServer(Configuration.GetConnectionString("LocalhostConnection"))
    );

我的错误是“IServiceProvider 不包含 UseSqlServer 的定义”

最佳答案

在这种情况下,您需要在工厂委托(delegate)中创建一个实例

string connectionString = Configuration.GetConnectionString("LocalhostConnection");
services.AddTransient<ICommanderRepo, DataClass>(provider => 
    new DataClass(connectionString)
);

传入所需的构造函数参数。

关于c# - .Net core将SqlConnection注入(inject)到服务中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63858495/

相关文章:

c# - 当 DropDownList Filter 的值不是 ALL 时,如何删除 GridView 中的整个第一列?

c# - 如果 sibling 不能,为什么 parent 可以访问子类的 protected 成员的实例?

c# - 类成员的自定义属性

c# - 多个中间件(REST + SOAP)

c# - 使用字符串作为 Id 测试详细信息操作

c# - IIS 中的 RSA 容器返回 "Object already exists"

c# - Windows.Forms Visual Studio,如何直接在第一个窗口上打开第二个窗口?

c# - php中的友元函数是什么?

asp.net-core - .Net core api 与 AD B2C OAuth 2.0 - Invalid_token 错误

asp.net-core - .Net Core 中的 Big-Endian 处理