MVC Base Controller and Ninject - asp.net-mvc

I am implementing Ninject dependency injection in an existing MVC 2 application that uses a base controller that all controllers inherit to set navigation and other information needed by the master page. When I set a controller to inherit from the base controller, I get the following error: "...BaseController' does not contain a constructor that takes 0 arguments. How do I get around this error? I am new to Ninject and can't figure this out.
public class BaseController : Controller
{
private INavigationRepository navigationRepository;
private ISessionService sessionService;
public BaseController(INavigationRepository navigationRepository, IMembershipService membershipService, ISessionService sessionService)
{
this.navigationRepository = navigationRepository;
this.sessionService = sessionService;
}
}
public class HomeController: BaseController
{ ... }

Adding that ctor is one way
public class HomeController: BaseController
{
public HomeController(INavigationRepository navigationRepository, IMembershipService membershipService, ISessionService sessionService)
: base(navigationRepository, membershipService, sessionService) { }
}
or property injection
public class BaseController : Controller
{
[Inject]
public INavigationRepository navigationRepository { get; set; }
[Inject]
public ISessionService sessionService { get; set; }
}

Related

Effect in application performance by Repository pattern and Unit of work with entity framework in asp.net mvc

I am working with a database where I have more than 75 tables and I am using the repository and unit of work patterns with Entity Framework in an ASP.NET MVC project. I am little bit confused and some query in my mind about object creation. When UnitOfWork initializes, it creates object for all table's entity which is present in UnitOfWork. So it can be heavy for application load.
Here is the interface of unit of work:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Application.Repository;
using Application.Repository.General;
namespace Application.UnitOfWorks
{
public interface IUnitOfWork : IDisposable
{
IGeneralRegionMasterRepository GeneralRegionMasters { get; }
IGeneralSubRegionMasterRepository GeneralSubRegionMasters { get; }
IGeneralCountryMasterRepository GeneralCountryMasters { get; }
IGeneralStateMasterRepository GeneralStateMasters { get; }
IGeneralCityMasterRepository GeneralCityMasters { get; }
int Complete();
}
}
Implementation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Application.EntityFramework;
using Application.Repository;
using Application.Repository.General;
namespace Application.UnitOfWorks
{
public class UnitOfWork : IUnitOfWork
{
public readonly InventoryDbContext _context;
public UnitOfWork(InventoryDbContext context)
{
_context = context;
GeneralRegionMasters = new GeneralRegionMasterRepository(_context);
GeneralSubRegionMasters = new GeneralSubRegionMasterRepository(_context);
GeneralCountryMasters = new GeneralCountryMasterRepository(_context);
GeneralStateMasters = new GeneralStateMasterRepository(_context);
GeneralCityMasters = new GeneralCityMasterRepository(_context);
}
public IGeneralRegionMasterRepository GeneralRegionMasters { get; private set; }
public IGeneralSubRegionMasterRepository GeneralSubRegionMasters { get; private set; }
public IGeneralCountryMasterRepository GeneralCountryMasters { get; private set; }
public IGeneralStateMasterRepository GeneralStateMasters { get; private set; }
public IGeneralCityMasterRepository GeneralCityMasters { get; private set; }
public int Complete()
{
return _context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
}
I want to know about performance effect of it on application. Thank you in advance for help.
I've run into the same problem that you are describing in the past. The structure of the code just feels really heavy since you are creating new instances of 70 repositories even though you may only need one of them. This is why I've just started to avoid adding my own UoW and Repositories when using EF directly because EF already has Repositories and UoW built in (DbSets = Repos, Save Changes does UoW save at the end of all DbSet changes). If you don't want to code directly against a DbContext, just have your DbContext implement the IUnitOfWork interface directly and go off of that. Also have all your DbSets exposed on that UnitOfWork. Then you could have it also implement IMyDbContext and have that expose the DbSets and have this interface also implement IUnitOfWork (or have DbContext -> IMyDbContext -> IUnitOfWork) or break them up if you don't want repo code having access to Save at the bottom. This just ends up making it easier in the long run. No weird code to maintain, no classes to create. If you switch to not use EF, you can still use those same interfaces behind the scenes and the only thing that would have to change would be the DbSet implementation (maybe you can even get that to be generic - create your on DbSets that implement another interface, too). Personally, I'm going down the CQS path so I don't have to worry about repos or UoW anymore. :)
Edit
Example the best I can here! :)
public interface IUnitOfWork
{
int Complete();
Task<int> CompleteAsync();
}
public interface IInventoryDbContext : IUnitOfWork
{
DbSet<GeneralRegionMaster> GeneralRegionMasters { get; }
DbSet<GeneralSubRegionMaster> GeneralSubRegionMasters { get; }
... etc
}
public class MyDbContext : DbContext, IInventoryDbContext
{
public DbSet<GeneralRegionMaster> GeneralRegionMasters { get; set; }
public DbSet<GeneralSubRegionMaster> GeneralSubRegionMasters { get; set;
}
public int Complete() => this.SaveChanges();
public Task<int> CompleteAsync() => this.SaveChangesAsync();
}
If you did a controller level only:
public class MyController : Controller
{
private readonly IInventoryDbContext _context;
public MyController(IInventoryDbContext context)
{
_context = context;
}
public JsonResult CreateGeneralRegionMaster(GeneralRegionMaster entity)
{
_context.GeneralRegionMaster.Add(entity);
var result = _context.Complete();
return Json(result == 1);
}
}
Again, you could do something different for the DbSets and do this instead:
public interface IRepo<T> where T: class
{
// Expose whatever methods you want here
}
public class MyDbSet<T> : DbSet<T>, IRepo<T> where T: class
{
}
Then this changes:
public interface IInventoryDbContext : IUnitOfWork
{
IRepo<GeneralRegionMaster> GeneralRegionMasters { get; }
IRepo<GeneralSubRegionMaster> GeneralSubRegionMasters { get; }
... etc
}
public class MyDbContext : DbContext, IInventoryDbContext
{
public MyDbSet<GeneralRegionMaster> GeneralRegionMasters { get; set; }
public MyDbSet<GeneralSubRegionMaster> GeneralSubRegionMasters { get; set; }
public IRepo<GeneralRegionMaster> GeneralRegionMastersRepo => GeneralRegionMasters;
public IRepo<GeneralSubRegionMaster> GeneralSubRegionMastersRepo => GeneralSubRegionMasters;
public int Complete() => this.SaveChanges();
public Task<int> CompleteAsync() => this.SaveChangesAsync();
}
Re:
When UnitOfWork initializes, it creates object for all table's entity which is present in UnitOfWork. So it can be heavy for application load.
You don't need to initialize all the repo instances in the UoW constructor.
You can create them when they are required in the corresponding getters (lazy initialization):
private IGeneralRegionMasterRepository _generalRegionMasters;
public IGeneralRegionMasterRepository GeneralRegionMasters {
get {
if (_generalRegionMasters == null) {
_generalRegionMasters = new GeneralRegionMasterRepository(_context);
}
return _generalRegionMasters;
}
}

How To Use CRUD in ASP.Net MVC with EntityFramework CodeFirst in Pattern IUnitofwork

I Have a PhoneBook Project in MVC and use IUnitOfWork .
but I dont Know that How do this project.
the link of the project :
http://www.mediafire.com/download/jy0b5ins5eisy5t/MvcAppPhoneBook.rar
please complate thie project for me
i'm doing CRUD in this project.
I've used generic repo and UoW in my projects as below. You can take reference of this to complete your project. I usually have 4 layer solution architecture:
Core
Model classes
Data
Generic Repo and UoW
DbContext
Code first migrations
Web
applications solution with dependency injection implementation (e.g.Ninject)
Test
Model classes
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
}
MyDbContext.cs:
public class MyDbContext : DbContext
{
public MyDbContext() : base("name=DefaultConnection”)
{
}
public System.Data.Entity.DbSet<User> Users { get; set; }
public System.Data.Entity.DbSet<Course> Courses { get; set; }
}
Unit of Work:
public class UnitOfWork : IUnitOfWork
{
//private variable for db context
private MyDbContext _context;
//initial db context variable when Unit of Work is constructed
public UnitOfWork()
{
_context = new MyDbContext();
}
//property to get db context
public MyDbContext Context
{
//if not null return current instance of db context else return new
get { return _context ?? (_context = new MyDbContext()); }
}
//save function to save changes using UnitOfWork
public void Save()
{
_context.SaveChanges();
}
}
Generic Repository:
public class RepositoryBase<T> : IRepositoryBase<T> where T : class
{
protected readonly IUnitOfWork _unitOfWork;
private readonly IDbSet<T> _dbSet;
public RepositoryBase(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_dbSet = _unitOfWork.Context.Set<T>();
}
public virtual void Save()
{
_unitOfWork.Save();
}
public virtual void Add(T entity)
{
_dbSet.Add(entity);
_unitOfWork.Save();
}
//Similarly you can have Update(), Delete(), GetAll() implementation here
}
Entity Repository inheriting from generic repo:
public class UserRepository:RepositoryBase<User>,IUserRepository
{
public UserRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
{
}
//Here you can also define functions specific to User
}
controller.cs
public class UserController : Controller
{
private readonly IUserRepository _dbUserRepository;
public UserController(IUserRepository dbUserRepository)
{
_dbUserRepository = dbUserRepository;
}
// GET: /User/
public ActionResult Index()
{
var users = _dbUserRepository.GetAll();
return View(users.ToList());
}
//Other CRUD operations
}

Interface usage on controller implementation

I'm using MVC pattern in my application. For each model class I have a controller one. All controller classes have a saveOrUpdate() method. I am wondering if this is enough to create an Interface which defines said method, and then all controller implements it.
Please note that saveOrUpdate() receive a model class as a parameter. So it would be something like UserController#saveOrUpdate(User user), CourseController#saveOrUpdate(Course course), AppleManager#saveOrUpdate(Apple apple).
I think what you need is generic repository which implements generic functionality for a given entity. I've recently started implementing Repository Pattern along with Unit of Work in my MVC projects. Here is how I do that.
MyDbContext.cs:
public class MyDbContext : DbContext
{
public MyDbContext() : base("name=DefaultConnection”)
{
}
public System.Data.Entity.DbSet<User> Users { get; set; }
public System.Data.Entity.DbSet<Course> Courses { get; set; }
}
Unit of Work:
public class UnitOfWork : IUnitOfWork
{
//private variable for db context
private MyDbContext _context;
//initial db context variable when Unit of Work is constructed
public UnitOfWork()
{
_context = new MyDbContext();
}
//property to get db context
public MyDbContext Context
{
//if not null return current instance of db context else return new
get { return _context ?? (_context = new MyDbContext()); }
}
//save function to save changes using UnitOfWork
public void Save()
{
_context.SaveChanges();
}
}
Generic Repository:
public class RepositoryBase<T> : IRepositoryBase<T> where T : class
{
protected readonly IUnitOfWork _unitOfWork;
private readonly IDbSet<T> _dbSet;
public RepositoryBase(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_dbSet = _unitOfWork.Context.Set<T>();
}
public virtual void Save()
{
_unitOfWork.Save();
}
public virtual void Add(T entity)
{
_dbSet.Add(entity);
_unitOfWork.Save();
}
//Similarly you can have Update(), Delete(), GetAll() implementation here
}
Entity Repository inheriting from generic repo:
public class UserRepository:RepositoryBase<User>,IUserRepository
{
public UserRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
{
}
//Here you can also define functions specific to User
}
Controller:
public class UserController : Controller
{
private readonly IUserRepository _dbUserRepository;
public UserController(IUserRepository dbUserRepository)
{
_dbUserRepository = dbUserRepository;
}
// GET: /User/
public ActionResult Index()
{
var users = _dbUserRepository.GetAll();
return View(users.ToList());
}
}
create an interface
interface ISave
{
void Save(object obj);
}
now in your controller implement it.
public class AppleControler : Controller , ISave
{
public void Save(Object obj)
{
//you can cast your object here.
}
}
Option two
interface ISave<T>
{
void Save(T obj);
}
public class AppleControler : Controller , ISave<Apple>
{
public void Save(Apple obj)
{
}
}

best practice to implement repository pattern and unitOfWork in ASP.NET MVC [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am working on implementing Repository Pattern and UnitOfWork from last few days, which I have completed to upto good extend, I believe. I am sure there are plenty of ways to implement that but what I am interesting to find best approach for that.
I am taking very simple example coded in ASP.NET MVC 5 using visual studio 2013. my main focus of question is implementation of UnitOfWork. is it advisable to use multiple UnitOfWorks for each business concerns implementing repository functions in private method and giving away public functions for controller to use????
I have function table (SQL Server) in the controller class via generic repository. I have IGenericRepository which has IQueryable one function, I have GenericRepository class where i am implementing this interface. I got FunctionContext which is inherited from baseContext. The reason i have baseContext so all the dbcontexts can use one path to hit database but same time keep number of table limited to business need.
now in my approach;
One BaseContext : DbContext
multiple DbContext, bundling all required table to individual business concern that extend BaseContext
Generic Repository Interface (CRUD)
Generic Repository Implementation class
specific Repository class, extending Generic Reposirtory in case require more function on top of CRUD operations.
Individual UnitOfWork --> taking to required repository/ repositories in private method and provide public method only for using functions
Controller call require UnitOfWork to use public methods.
in following program, all i am getting list of function title and passing to controller to print
Generic Repository Interface
public interface IGenericRepository<TEntity> : IDisposable
{
IQueryable<TEntity> GetAll();
}
Generic Repository
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
protected DbSet<TEntity> _DbSet;
private readonly DbContext _dbContext;
public GenericRepository()
{
}
public GenericRepository(DbContext dbContext)
{
this._dbContext = dbContext;
_DbSet = _dbContext.Set<TEntity>();
}
public IQueryable<TEntity> GetAll()
{
return _DbSet;
}
public void Dispose()
{
}
}
BaseContext
public class BaseContext<TContext> : DbContext where TContext : DbContext
{
static BaseContext()
{
Database.SetInitializer<TContext>(null);
}
protected BaseContext()
: base("name = ApplicationDbConnection")
{ }
}
FunctionContext
public class FunctionsContext : BaseContext<FunctionsContext>
{
public DbSet<App_Functions> Functions { get; set; }
}
Function Mapping class
[Table("Functions")]
public class App_Functions
{
public App_Functions()
{
}
[Key]
public int Function_ID { get; set; }
[StringLength(50)]
[Required]
public string Title { get; set; }
public int Hierarchy_level { get; set; }
}
Function Domain class
public class Functions
{
public Functions()
{
}
public int Function_ID { get; set; }
public string Title { get; set; }
public int Hierarchy_level { get; set; }
}
Function_UnitOfWork
public class Function_UnitOfWork
{
private GenericRepository<App_Functions> _function_Repository = new GenericRepository<App_Functions>(new FunctionsContext());
public Function_UnitOfWork()
{
}
private List<Functions> getAllFunctionsFromRepository()
{
List<Functions> query = new List<Functions>();
query = _function_Repository.GetAll().Select(x => new Functions
{
Function_ID = x.Function_ID,
Title = x.Title,
Hierarchy_level = x.Hierarchy_level
}).ToList();
return query;
}
public List<Functions>GetAllFunctions()
{
return getAllFunctionsFromRepository();
}
}
Controller class
public class HomeController : Controller
{
public ActionResult Index()
{
Function_UnitOfWork UOF = new Function_UnitOfWork();
var a1 = UOF.GetAllFunctions();
foreach(var item in a1)
{
var b1 = item.Title;
}
return View();
}
}
While it is opinion based, just the name of of Unit Of Work pattern suggest limited timespan of the object. So the use of it in controller should be something like
public ActionResult Index()
{
using(var UOF = new Function_UnitOfWork()) {
var a1 = UOF.GetAllFunctions();
foreach(var item in a1)
{
var b1 = item.Title;
}
}
return View();
}
Also one approach we use is (in short)
public class DataObject { }
public class Repo: IRepo<T> where T: DataObject
public class RepoController<T> : Controller where T: DataObject {
protected IRepo<T> Repo;
}
So controllers will be generic and will have field for particular repo
You will use some dependency injection tool, like ninject or mef to bound controllers with repos behind the scene.

Ninject not binding object in BaseController in MVC3

I just upgraded my MVC2 project to MVC3 and used the NuGet library package reference to install ninject. This created an appstart class and i used the following code to inject my IMembershipService class.
public static void RegisterServices(IKernel kernel) {
kernel.Bind<IMembershipService>().To<AccountMembershipService>();
}
This works great with my HomeController, for example.
public class HomeController : Controller
{
public IMembershipService MembershipService { get; set; }
public HomeController() : this(null) { }
public HomeController(IMembershipService service)
{
MembershipService = service;
}
HOWEVER, I am using a BaseController. Nearly the same code in the base class no longer works.
public class BaseController : Controller
{
public IMembershipService MembershipService { get; set; }
public UserService UserService { get; set; }
public BaseController() : this(null, null) { }
public BaseController(IMembershipService service, UserService userService)
{
MembershipService = service;
UserService = userService ?? new UserService();
}
If I break in the constructor of the base controller, service is just NULL. I have never used Ninject for IOC so perhaps the answer is obvious, but why will it not inject my AccountMembershipController in the base class like I want it to? I don't see what is different, although i realize the extra level of inheritance may be messing with Ninject somehow.
Your HomeController dervices from Controller, not BaseController? Also, you have a default constructor for BaseController that sets things as null. Why do you have that at all? I'd start by getting rid of those default constructors. You shouldn't need any default constructors.
I ran into this same problem myself. Assuming your code looks like this:
public HomeController : BaseController
{
}
public BaseController : Controller
{
public IMembershipService MembershipService { get; set; }
public MembershipService() { }
public MembershipService(IMembershipService service)
{
MembershipService = service;
}
}
For some reason, Ninject thinks that HomeController only has one constructor, the default parameterless one. When you put everything in HomeController, it can find the injectable constructor, but factor it out into a base class and for some reason it won't look in the base class to see if there are any overloaded constructors. There are two fixes for this:
Remove the default constructor. This is my preferred solution because it forces the constructor to be injected (like when you create the controller manually when unit testing), but the downside is that you have to implement the constructor in all your subclasses.
Keep the default constructor, but add the [Inject] attribute to all your injectable properties:
public BaseController : Controller
{
[Inject] public IMembershipService MembershipService { get;set; }
// rest is the same
}
Ninject will inject the properties correctly this way, but be aware that Ninject will call the parameterless constructor.

Resources