0

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

Mou
  • 15,673
  • 43
  • 156
  • 275
  • You will need a DI framework (such as Ninject, but there are lots of them) that will inject the concrete class (`UsersRepository`) into the controller –  Sep 07 '15 at 09:29
  • tell me what additional code i need to plug in and where? – Mou Sep 07 '15 at 09:37
  • how to inject repository instance when controller will be called. – Mou Sep 07 '15 at 09:38
  • @Mou check top answer. DI is a framework, that enables you to inject concrete classes via interfaces that have been registerered such as your IUserRepository – JEV Sep 07 '15 at 09:58
  • possible duplicate of [Constructor Dependency Injection in a ASP.NET MVC Controller](http://stackoverflow.com/questions/1338271/constructor-dependency-injection-in-a-asp-net-mvc-controller) – CodeCaster Sep 07 '15 at 10:12
  • 1
    Did you try educating yourself? Starting from scratch with MVC and deep diving into repository pattern and dependency injection can be a bit too much, which will lead to a lot of too broad questions according to your track record where picking up new technologies. Dependency injection in general and for MVC specifically has been documented **very thoroughly** on the web, yet again you're asking "explain this in words I can understand". Can you try showing a little more effort? – CodeCaster Sep 07 '15 at 10:15

1 Answers1

1

This work can be done using Dependency Injection(DI) framework.

DI - removes the responsibility of direct creation, and management of the lifespan, of other object instances upon which our class of interest (consumer class) is dependent (in the UML sense). These instances are instead passed to our consumer class, typically as constructor parameters or via property setters (the management of the dependency object instancing and passing to the consumer class is usually performed by an Inversion of Control (IoC) container, but that's another topic).

For more details you can read the article: ASP.NET MVC 4 Dependency Injection.
Also I recommend you read the book Pro ASP.NET MVC by Adam Freeman, that describes very well work with DI container such as Ninject.
And please see What is dependency injection?

I give a small example:
We created two constructors, first is without parameter for unit-testing:

public BaseApiController()
{
   repository = unitOfWork.EFRepository<T>();
}

And the second constructor with dependency injection:

public BaseApiController(IRepository<T> repository)
{
  this.repository = repository;
}

Then for using DI container like Ninject we need to create and configure Controller Factory:

    public class NinjectControlFactory : DefaultControllerFactory
    {
        private IKernel ninjectKernel;
        public NinjectControlFactory()
        {
            //create container
            ninjectKernel = new StandardKernel();
            AddBindings();
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            return controllerType == null
                ? null
                : (IController)ninjectKernel.Get(controllerType);
        }

        private void AddBindings()
        {
            //congif container
            ninjectKernel.Bind(typeof(IRepository<>)).To(typeof(EFRepository<>));
        }
    }

Finally we have to register the container in Application_Start()of Global.asax file :

ControllerBuilder.Current.SetControllerFactory(new NinjectControlFactory());
Community
  • 1
  • 1
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
  • i am not advance developer and that is why i do not understand ninject related code. i just do not understand how dependency called `IRepository repository` is getting injected. thanks – Mou Sep 07 '15 at 10:48
  • 1
    Here's a good [beginner's tutorial on dependency injection with Ninject and MVC3](http://stevescodingblog.co.uk/dependency-injection-beginners-guide/) – Roman Marusyk Sep 07 '15 at 11:11
  • We are creating a Ninject Kernel that resolves our entire chain of dependencies. We tell Ninject to load the bindings from the executing assembly. This is the most common scenario. More information how works Ninject https://github.com/ninject/ninject/wiki – Roman Marusyk Sep 07 '15 at 11:13