简体   繁体   中英

.Net core injecting SqlConnection into service

I'm trying to write a really simple CRUD api using sql server but NOT USING EF .

my data class looks like this

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;
    }
 }

which I think will work fine. However, I'm doing something wrong when I set up the service in my startup.cs

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

my error is "IServiceProvider does not contain a definition for UseSqlServer"

In this case you would need to create an instance in the factory delegate

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

passing in the desired constructor arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM