i am new in MVC. so i was reading a article on repository design pattern
and one thing comes before my eyes which is not clear. here is the code...first see the code.
public interface IUsersRepository
{
public User GetUser(int id);
}
then implement it:
public class UsersRepository: IUsersRepository
{
private readonly string _connectionString;
public UsersRepository(string connectionString)
{
_connectionString = connectionString;
}
public User GetUser(int id)
{
// Here you are free to do whatever data access code you like
// You can invoke direct SQL queries, stored procedures, whatever
using (var conn = new SqlConnection(_connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT id, name FROM users WHERE id = @id";
cmd.Parameters.AddWithValue("@id", id);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
{
return null;
}
return new User
{
Id = reader.GetInt32(reader.GetOrdinal("id")),
Name = reader.GetString(reader.GetOrdinal("name")),
}
}
}
}
}
and then your controller could use this repository:
public class UsersController: Controller
{
private readonly IUsersRepository _repository;
public UsersController(IUsersRepository repository)
{
_repository = repository;
}
public ActionResult Index(int id)
{
var model = _repository.GetUser(id);
return View(model);
}
}
see the controller code. when an user request page like Users\index\10
then this action will be called public ActionResult Index(int id){}
my question is how this method will work _repository.GetUser(id); ?
because when ctor
UsersController()
will be called then how the repository instance will be pass there ?
my question is if any class has parameterize
constructor then we need to pass parameter value when we need to create instance of that class.
in this case controller constructor
is parameterize
so when user will request a page like Users\index\10
then controller constructor will be called but how parameter will be passed there............this is not clear to me.
please help me to understand. thanks