I'm trying out asp.net out and I'm having issues doing the simplest thing, connecting to a database. I have no clue how to call my context via dependency injection to use in my repository, if anyone can help me out it would be great. Here is my code:
Model:
public class User
{
...attrs...
}
Interface / Repo:
public interface UserRepository
{
List<User> GetUsers();
}
public class UserRepositoryImpl : UserRepository
{
public List<User> GetUsers()
{
//I NEED THE CONTEXT FOR "db" HERE!
using (MySqlConnection con = db.GetConnection())
{
List<User> list = new List<User>();
con.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM user", con);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new User()
{
...read stuff...
});
}
}
return list;
}
}
}
My Context:
public class MyContext
{
public string ConnectionString { get; set; }
public MyContext(string connectionString)
{
this.ConnectionString = connectionString;
}
public MySqlConnection GetConnection()
{
return new MySqlConnection(ConnectionString);
}
}
Service registration:
services.Add(new ServiceDescriptor(typeof(MyContext), new MyContext(Configuration.GetConnectionString("DefaultConnection"))));
Most tutorials either force me to use EF and others don't do the dependency injection, if anyone could guide me or point me to the right direction I would be really greatful! Thanks in advance!
EDIT: I got it to work using this in my controller after creating a constructor that takes in the context for my db:
[Produces("application/json")]
[Route("api/user")]
public class UserController : Controller
{
[HttpGet]
public List<User> AllUsers()
{
MyContext db = HttpContext.RequestServices.GetService(typeof(MyContext)) as MyContext;
UserRepositoryImpl repo = new UserRepositoryImpl(db);
return repo.GetUsers();
}
}
I still believe this can be improved though, is there a better way to do this? Thanks
EDIT2: Finally got it to work using this controller
[Produces("application/json")]
[Route("api/user")]
public class UserController : Controller
{
MyContext db;
public UserController(MyContext db)
{
this.db = db;
}
[HttpGet]
public List<User> AllUsers()
{
UserRepository repo = new UserRepository(db);
return repo.GetUsers();
}
}
Thanks to Tseng's answer!