我正在尝试使用 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/