Search code examples
asp.net-mvc-3dependency-injectionninject.web.mvc

Ninject, Repository and DAL


I am new to MVC, repository concept and dependency injection.

My repository and DAL looks like

public interface IRepository<TEntity> where TEntity : class
{
    List<TEntity> FetchAll();
    IQueryable<TEntity> Query { get; }
    void Add(TEntity entity);
    void Delete(TEntity entity);
    void Save();
}


public class Repository<T> : IRepository<T> where T : class
{
    private readonly DataContext _db;

    public Repository(DataContext db)
    {
        _db = db;
    }

    #region IRepository<T> Members

    public IQueryable<T> Query
    {
        get { return _db.GetTable<T>(); }
    }

    public List<T> FetchAll()
    {
        return Query.ToList();
    }

    public void Add(T entity)
    {
        _db.GetTable<T>().InsertOnSubmit(entity);
    }

    public void Delete(T entity)
    {
        _db.GetTable<T>().DeleteOnSubmit(entity);
    }

    public void Save()
    {
        _db.SubmitChanges();
    }

    #endregion
}

In Global.asax file I have

    private void RegisterDependencyResolver()
    {
        var kernel = new StandardKernel();
        kernel.
            Bind(typeof(IRepository<>)).
            To(typeof(Repository<>))
            .WithConstructorArgument("db", new DataContext(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()));
        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
    }

but when I am trying to access repository I get "Object reference not set to an instance of an object". Do I understand correctly how Repository and Injection should work?

 public class AdminController : Controller
    {

       private readonly IRepository<User> _userRepository;

        public ActionResult Index()
        {
            var a = _userRepository.FetchAll(); //I get exception here
            return View();
        }
}

Solution

  • You get nullref because you don't set _userRepository. Set it in the AdminControllers constructor and Niject will inject it happily:

    public class AdminController : Controller
    {
        private readonly IRepository<User> _userRepository;
        public AdminController(IRepository<User> userRepository)
        {
            _userRepository = userRepository;
        }
    
        //...
    }
    

    You can read here more about the injection patterns with Ninject and how injection works.