EF 6 - Ninject - The operation cannot be completed because the dbcontext has been disposed - asp.net-web-api

I've seen a lot of questions with this error, so sorry for asking again, but no solutions have worked for me so far.
I'm working on a ASP.NET Web API project that's using the Ninject and Ninject.Web.Common references, where a DbContext is injected into the repositories. This error pops up the second time I send a request subsequently.
My stack trace :
at System.Data.Entity.Internal.InternalContext.CheckContextNotDisposed()
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.LazyInternalContext.get_ObjectContext()
at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force)
at System.Data.Entity.Internal.InternalContext.GetStateEntries(Func`2 predicate)
at System.Data.Entity.Internal.InternalContext.GetStateEntries()
at System.Data.Entity.Infrastructure.DbChangeTracker.Entries()
at Project.Data.UnitOfWork.Commit() in c:\Projects\Project\src\DotNet\Project.Data\UnitOfWork.cs:line 22
at Project.Api.Infrastructure.UnitOfWorkAttribute.OnActionExecuted(HttpActionExecutedContext actionExecutedContext) in c:\Projects\Project\src\DotNet\Project.Api\Infrastructure\UnitOfWorkAttribute.cs:line 25
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__1.MoveNext()
Ninject : RegisterServices
kernel.Bind<DataContextFactory>().ToSelf().InRequestScope().WithConstructorArgument("nameOrConnectionString", "Project");
kernel.Bind<DataContext>().ToMethod(context => kernel.Get<DataContextFactory>().GetContext()).InRequestScope();
kernel.Bind<IRepository<Device>>().To<Repository<Device>>();
kernel.Bind<IRepository<Person>>().To<Repository<Person>>();
kernel.Bind<UnitOfWork>().ToSelf().InRequestScope();
kernel.BindHttpFilter<UnitOfWorkAttribute>(FilterScope.Controller).WhenControllerType<DeviceController>();
kernel.BindHttpFilter<UnitOfWorkAttribute>(FilterScope.Controller).WhenControllerType<PersonController>();
My IRepositiry class
public interface IRepository<TAggregateRoot> where TAggregateRoot : class, IAggregateRoot
{
void Save(TAggregateRoot instance);
void Remove(TAggregateRoot instance);
TAggregateRoot One(Expression<Func<TAggregateRoot, bool>> predicate = null, params Expression<Func<TAggregateRoot, object>>[] includes);
IQueryable<TAggregateRoot> All(Expression<Func<TAggregateRoot, bool>> predicate = null, params Expression<Func<TAggregateRoot, object>>[] includes);
bool Exists(Expression<Func<TAggregateRoot, bool>> predicate = null);
int Count(Expression<Func<TAggregateRoot, bool>> predicate = null);
}
My person controller class
public class PersonController : ApiController
{
private readonly IRepository<Person> _personRepository;
public PersonController(IRepository<Person> personRepository)
{
_personRepository = personRepository;
}
...
}
My DbContext
private readonly IDictionary _configurations;
public DataContext(string nameOrConnectionString, IDictionary<MethodInfo, object> configurations)
: base(nameOrConnectionString)
{
_configurations = configurations;
}
public virtual void MarkAsModified<TEntity>(TEntity instance) where TEntity : class
{
Entry(instance).State = EntityState.Modified;
}
public virtual IDbSet<TEntity> CreateSet<TEntity>() where TEntity : class
{
return Set<TEntity>();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if (modelBuilder == null)
{
throw new ArgumentNullException("modelBuilder");
}
foreach (var config in _configurations)
{
config.Key.Invoke(modelBuilder.Configurations, new[] { config.Value });
}
base.OnModelCreating(modelBuilder);
}

Related

ASP.NET Web Api and Autofac IoC. Error: ExceptionMessage=None of the constructors found

I am trying to use Autofac for IoC for my Asp.Net WebApi project. I am trying to send a simple POST request to the API, but to no avail. I have been stuck on this for some time now and can't figure it out.
Please see relevant code and advise accordingly. Your help would be greatly appreciated.
public interface IEntityRepository<T> where T : class, new()
{
IQueryable<T> All { get; }
IQueryable<T> AllIncluding(params Expression<Func<T,object>>[] includeProperties);
IQueryable<T> GetAll();
//IQueryable<T> GetSingle(string entitiesID);
IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
void Add(T entity);
void Delete(T entity);
void Edit(T entity);
void Save();
PaginatedList<T> Paginate<TKey>(int pageindex, int pagesize, Expression<Func<T, TKey>> keySelector);
PaginatedList<T> Paginate<TKey>(
int pageindex, int pagesize,
Expression<Func<T, TKey>> keySelector,
Expression<Func<T, bool>> predicate,
params Expression<Func<T, object>>[] includeProperties);
}
public class EntityRepository<T> : IEntityRepository<T> where T : class, new()
{
readonly CirclesDBEntities _entitiesContext;
public EntityRepository(CirclesDBEntities entitiesContext)
{
if (entitiesContext == null)
{
throw new ArgumentNullException("entitiesContext");
}
_entitiesContext = entitiesContext;
}
public virtual IQueryable<T> GetAll()
{
return _entitiesContext.Set<T>();
}
public IQueryable<T> All
{
get { return GetAll(); }
}
public virtual IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = _entitiesContext.Set<T>();
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query;
}
public virtual IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
{
return _entitiesContext.Set<T>().Where(predicate);
}
public virtual PaginatedList<T> Paginate<TKey>(int pageIndex, int pageSize, Expression<Func<T, TKey>> keySelector)
{
return Paginate(pageIndex, pageSize, keySelector, null);
}
public virtual PaginatedList<T> Paginate<TKey>(
int pageIndex, int pageSize,
Expression<Func<T, TKey>> keySelector,
Expression<Func<T, bool>> predicate,
params Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = AllIncluding(includeProperties).OrderBy(keySelector);
query = (predicate == null) ? query : query.Where(predicate);
return query.ToPaginatedList(pageIndex, pageSize);
}
public virtual void Add(T entity)
{
DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
_entitiesContext.Set<T>().Add(entity);
}
public virtual void Edit(T entity)
{
DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
dbEntityEntry.State = EntityState.Modified;
}
public virtual void Delete(T entity)
{
DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
dbEntityEntry.State = EntityState.Deleted;
}
public virtual void Save()
{
_entitiesContext.SaveChanges();
}
}
public static class TermRepository
{
public static Term GetCurrentTerm(this IEntityRepository<Term> termRepository)
{
return termRepository.GetAll().OrderByDescending(x => x.DateUploaded).FirstOrDefault(); //descending puts the most recent item on top of the stack
}
}
public class TermsService : ITermsService
{
private readonly IEntityRepository<Term> _termRepository;
public TermsService(IEntityRepository<Term> termRepository)
{
_termRepository = termRepository;
}
public Term GetMostRecentTerm()
{
Term term = _termRepository.GetCurrentTerm();
return term;
}
public bool UploadNewTerm(string newTerm)
{
Term term = new Term();
term.TermID = SetAccountID();
term.Term1 = newTerm;
term.DateUploaded = DateTime.Now;
_termRepository.Add(term);
_termRepository.Save();
return true;
}
}
public interface ITermsService
{
Term GetMostRecentTerm();
bool UploadNewTerm(string Term);
}
public static class AutofacConfig
{
public static void Initialize(HttpConfiguration config)
{
Initialize(config,
RegisterServices(new ContainerBuilder()));
}
public static void Initialize(HttpConfiguration config, IContainer container)
{
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
private static IContainer RegisterServices(ContainerBuilder builder)
{
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// registration goes here
//EF DbContext
builder.RegisterType<CirclesDBEntities>()
.As<DbContext>()
.InstancePerRequest();
//Repositories
builder.RegisterGeneric(typeof(EntityRepository<>))
.As(typeof(IEntityRepository<>))
.InstancePerDependency();
//this makes it check non-public classes
//builder.RegisterGeneric(typeof(EntityRepository<>))
//.As(typeof(IEntityRepository<>))
//.InstancePerRequest().FindConstructorsWith(
//new DefaultConstructorFinder(type =>
//type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)))
//.As(typeof(IEntityRepository<>));
//Services
builder.RegisterType<TermsService>()
.As<ITermsService>()
.InstancePerRequest();
return builder.Build();
}
}
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//Registering routes from the WebApi.Config file
GlobalConfiguration.Configure(Config.WebApiConfig.Register);
//Registering routes from the HelpPageAreaRegistration in the areas section
GlobalConfiguration.Configure(CirclesWebApi.Areas.HelpPage.HelpPageAreaRegistration.RegisterAllAreas);
GlobalConfiguration.Configure(Config.AutofacConfig.Initialize);
}
}
public class TermsController : ApiController
{
public readonly ITermsService _termService;
public TermsController(ITermsService termService)
{
_termService = termService;
}
[HttpPost]
public HttpResponseMessage PostTerms()
{
string terms = "terms this is a new term inserted through fiddler";
if(terms != null)
{
bool created = _termService.UploadNewTerm(terms);
if (created)
{
var response = Request.CreateResponse(HttpStatusCode.Created);
return response;
}
else
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
}
Error:
ExceptionMessage=None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'
In the constructor of EntityRepository<T> you inject CirclesDBEntities, but you register it as DbContext. So you can fix this by injecting DbContext to the constructor, changing your registration by removing .As<DbContext>() part of your registration or by adding .AsSelf() to your registration.

Ninject Interception in WebAPI and parameterless constructor failing

I have an MVC4 site that uses both MVC and WebAPI in it. All was going well till I tried to change my classes to have a cross cutting AOP class that would help with caching data. I am now finding that when I call a method that does not have the InterceptAttribute on it, it will crash because Ninject didn't inject with a parameter, and it fails.
My BLL class looks like this:
public class FooBLL
{
#region Private Variables
private readonly IDAL _context;
#endregion
#region Constructor
public Foo(IDAL context)
{
_context = context;
}
#endregion
#region Public Methods
public List<Bar> GetAllBars()
{
return _context.GetAllBars();
}
public List<Bar> GetTwoBars()
{
return _context.GetTwoBars();
}
#endregion
}
My WebApi Controller looks like this:
public class FooController : ApiController
{
#region Private Variables
private readonly FooBLL _fooBll;
#endregion
#region Constructor
public FooController(FooBLL fooBll)
{
_fooBll = fooBll;
}
#endregion
#region Public Methods
#region Estimate Types
#region Get
public List<Bar> GetAllBars()
{
return _fooBll.GetAllBars();
}
public List<Bar> GetTwoBars()
{
return _fooBll.GetTwoBars();
}
#endregion
#endregion
#endregion
}
In my Website, I created the following Ninject classes for resolving the controllers:
public class NinjectRegistrations : NinjectModule
{
public override void Load()
{
Kernel.Bind<IDAL>().To<DAL>().InSingletonScope();
}
}
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver, System.Web.Mvc.IDependencyResolver
{
private readonly IKernel kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(this.kernel.BeginBlock());
}
}
public class NinjectDependencyScope : IDependencyScope
{
private IResolutionRoot resolver;
internal NinjectDependencyScope(IResolutionRoot resolver)
{
Contract.Assert(resolver != null);
this.resolver = resolver;
}
public void Dispose()
{
var disposable = this.resolver as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
this.resolver = null;
}
public object GetService(Type serviceType)
{
if (this.resolver == null)
{
throw new ObjectDisposedException("this", "This scope has already been disposed");
}
return this.resolver.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (this.resolver == null)
{
throw new ObjectDisposedException("this", "This scope has already been disposed");
}
return this.resolver.GetAll(serviceType);
}
}
In Global.asax I then register this resolver:
NinjectHelper.Kernel = new StandardKernel(modules);
var ninjectResolver = new NinjectDependencyResolver(NinjectHelper.Kernel);
DependencyResolver.SetResolver(ninjectResolver); // MVC
GlobalConfiguration.Configuration.DependencyResolver = ninjectResolver; // Web API
//Register Filter Injector
GlobalConfiguration.Configuration.Services.Add(typeof(System.Web.Http.Filters.IFilterProvider), new NinjectWebApiFilterProvider(NinjectHelper.Kernel));
Things were fine till I added the attribute Cache using Ninject.Extensions.Interception.Attributes.InterceptAttribute.
The class now looks like this (note that I added a parameterless constructor and marked one of the methods as virtual, these are both required for the Interception to work):
public class FooBLL
{
#region Private Variables
private readonly IDAL _context;
#endregion
#region Constructor
public Foo(IDAL context)
{
_context = context;
}
public Foo()
{
}
#endregion
#region Public Methods
public List<Bar> GetAllBars()
{
return _context.GetAllBars();
}
[Cache(DefaultTimeoutMinutes = 20)]
public virtual List<Bar> GetTwoBars()
{
return _context.GetTwoBars();
}
#endregion
}
Now on the WebAPI controller, when I call GetToBars(the method with the Intercept Attribute), everything still works fine.
However, when I call GetAllBars(the method that doesn't have the Intercept Attribute), I fail with an exception that _context is null.
Any help would be greatly appreciated.
Ben

Linq executing query generates not supported exception

I'm trying to execute a linq query in an extension method but I am getting the following exception on the ToArray() function call - it seems the query is having issues with my IList somehow, I have tried many different things and googled but fails to see the issue
An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: Cannot compare elements of type 'System.Collections.Generic.IList`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only primitive types, enumeration types and entity types are supported.
Code
public static IList<Shared.Poco.DimValue> ToDimValuePocoList(this IQueryable<DAL.DimValue> source)
{
IList<Shared.Poco.DimValue> values = new List<Shared.Poco.DimValue>();
foreach (DAL.DimValue dv in source.ToArray())
{
values.Add(new Shared.Poco.DimValue
{
DimensionId = dv.DimensionID,
DimValueName = dv.DimValueName,
DimValueNo = dv.DimValueNo
});
}
return values;
}
The class the calls the extension looks like this:
public class DimValue : IDimValue
{
private IDimValueRepository _repository;
private IAccessableDimensionValues _accessableDimensionValues;
private IRevision _revision;
public DimValue(IDimValueRepository reposotory, IAccessableDimensionValues accessableDimensionValues, IRevision revision)
{
_repository = reposotory;
_accessableDimensionValues = accessableDimensionValues;
_revision = revision;
}
public IList<Shared.Poco.DimValue> GetDimValueList(int budgetId, Shared.Poco.Dimension dimension, IList<string> dimensionValues, Shared.Poco.User user)
{
IList<Shared.Poco.DimValue> values = new List<Shared.Poco.DimValue>();
int budgetRevisionId = _revision.GetLatesRevision(budgetId);
IList<string> uniqueAccessableUBLValues = _accessableDimensionValues.GetUniqueAccessableDimensionValues(dimension, user.UserId, budgetRevisionId);
if (dimensionValues != null && dimensionValues.Count > 0)
{
uniqueAccessableUBLValues = dimensionValues;
}
return _repository.GetDimValueList(budgetId, dimension.ToString(), uniqueAccessableUBLValues, user).ToDimValuePocoList();
}
The implementation of the injected repository class inherits from the following base repository class
public interface IRepository<T>
{
void Insert(T entity);
void Delete(T entity);
IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate);
IQueryable<T> GetAll();
T GetById(int id);
}
public class Repository<T> : IRepository<T> where T : class
{
protected DbSet<T> DbSet;
public Repository(DbContext dataContext)
{
DbSet = dataContext.Set<T>();
}
#region IRepository<T> Members
public void Insert(T entity)
{
DbSet.Add(entity);
}
public void Delete(T entity)
{
DbSet.Remove(entity);
}
public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate)
{
return DbSet.Where(predicate);
}
public IQueryable<T> GetAll()
{
return DbSet;
}
public T GetById(int id)
{
return DbSet.Find(id);
}
#endregion
}
Repository implementation
public class DimValueRepository : Repository<DimValue>, IDimValueRepository
{
public DimValueRepository(KonstruktEntities context) : base(context) { }
public IQueryable<DimValue> GetDimValueList(int budgetId, string dimensionId, IList<string> dimensionFilter, Shared.Poco.User user)
{
return this.SearchFor(dv => dv.BudgetID == budgetId && dv.DimensionID == dimensionId &&
(dimensionFilter == null || dimensionFilter.Count == 0 || dimensionFilter.Contains(dv.DimValueNo)));
}
public IQueryable<DimValue> GetDimValueList(Shared.Poco.Dimension dimension, string startsWith, Shared.Poco.User user)
{
return this.SearchFor(dv=>dv.DimensionID == dimension.ToString() &&
dv.DimValueNo.StartsWith(startsWith));
}
}
EDIT
It's failing on the following row in the ToDimValuePocoList function:
foreach (DAL.DimValue dv in source.ToArray())
Here is the row calling the extension in the DimValue class
return _repository.GetDimValueList(budgetId, dimension.ToString(), uniqueAccessableUBLValues, user).ToDimValuePocoList();
Answered by #Will in the comment above, i.e. cannot use dimensionFilter in my predicate. So I moved that logic outside of the predicate.

"The type IUnitOfWork does not have an accessible constructor" with Umbraco 6.1, UmbracoApiController (Web API) & Dependency Injection (Unity)

I am using Umbraco 6.1 with an UmbracoApiController which has a IUnitOfWork injected into it's constructor. To inject the dependencies, I am using Unity, like I have in the past with standard Web API projects. Normally, I set unity up in the Global.asax.cs. As Umbraco does not have this I have created my own UmbracoEvents handler, which inherits from IApplicationEventHandler, and has the methods:
OnApplicationInitialized
OnApplicationStarting
OnApplicationStarted
ConfigureApi
In the OnApplicationStarted method I set up my EF database, db initializer etc and call ConfigureApi to set up Unity. My OnApplication Started and ConfigureApi methods looks like this:
public void OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
_applicationContext = applicationContext;
_umbracoApplication = umbracoApplication;
_contentService = ApplicationContext.Current.Services.ContentService;
this.ConfigureApi(GlobalConfiguration.Configuration);
Database.SetInitializer(null);
PropertySearchContext db = new PropertySearchContext();
db.Database.Initialize(true);
}
private void ConfigureApi(HttpConfiguration config)
{
var unity = new UnityContainer();
unity.RegisterType<PropertiesApiController>();
unity.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
config.DependencyResolver = new IoCContainer(unity);
}
My Controller code:
public class PropertiesApiController : UmbracoApiController
{
private readonly IUnitOfWork _unitOfWork;
public PropertiesApiController(IUnitOfWork unitOfWork)
{
if(null == unitOfWork)
throw new ArgumentNullException();
_unitOfWork = unitOfWork;
}
public IEnumerable GetAllProperties()
{
return new[] {"Table", "Chair", "Desk", "Computer", "Beer fridge"};
}
}
My Scope Container/IoC Container code: (as per http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver)
public class ScopeContainer : IDependencyScope
{
protected IUnityContainer container;
public ScopeContainer(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public object GetService(Type serviceType)
{
if (container.IsRegistered(serviceType))
{
return container.Resolve(serviceType);
}
else
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (container.IsRegistered(serviceType))
{
return container.ResolveAll(serviceType);
}
else
{
return new List<object>();
}
}
public void Dispose()
{
container.Dispose();
}
}
public class IoCContainer : ScopeContainer, IDependencyResolver
{
public IoCContainer(IUnityContainer container)
: base(container)
{
}
public IDependencyScope BeginScope()
{
var child = this.container.CreateChildContainer();
return new ScopeContainer(child);
}
}
My IUnitOfWork code:
public interface IUnitOfWork : IDisposable
{
GenericRepository<Office> OfficeRepository { get; }
GenericRepository<Property> PropertyRepository { get; }
void Save();
void Dispose(bool disposing);
void Dispose();
}
My UnitOfWork implementation:
public class UnitOfWork : IUnitOfWork
{
private readonly PropertySearchContext _context = new PropertySearchContext();
private GenericRepository<Office> _officeRepository;
private GenericRepository<Property> _propertyRepository;
public GenericRepository<Office> OfficeRepository
{
get
{
if (this._officeRepository == null)
{
this._officeRepository = new GenericRepository<Office>(_context);
}
return _officeRepository;
}
}
public GenericRepository<Property> PropertyRepository
{
get
{
if (this._propertyRepository == null)
{
this._propertyRepository = new GenericRepository<Property>(_context);
}
return _propertyRepository;
}
}
public void Save()
{
_context.SaveChanges();
}
private bool disposed = false;
public virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
I have used unity/DI with MVC4/WebAPI controllers and this implementation of UnitOfWork many times before without issue, so I'm thinking it's Umbraco specific.
I have also debugged the application and made sure that it hits OnApplicationStarted and that its parameters are not null.
The GetAllProperties method in the controller is just a test method to make sure it is all working fine, however, when I try and access this action I get the error:
"The type IUnitOfWork does not have an accessible constructor"
Does anyone have experience with using Umbraco 6.1 and it's UmbracoApiController with dependency injection/Unity?
Also, on an unrelated note, is there a way to return JSON instead of XML in the action? In Web API you would just define the formatter in the WebApi.config but there is none in Umbraco.
Thanks,
Justin
In case you haven't found a solution to your problem? Download this nuget package and right after building your unity container:
GlobalConfiguration.Configuration.DependencyResolver =
new Unity.WebApi.UnityDependencyResolver(Bootstrapper.Container);
Notice the namespace which is different than Unity.Mvc4.UnityDependencyResolver.

Do I need a Repository Class if I have a Service class and IRepository?

After reading, this question. I figured I need to look over my structure to avoid redundant code.
My current structure is Controller -> Repository -> IRepository.
The repository looks like this:
public class UserRepository : IUserRepository, IDisposable
{
private StudentSchedulingEntities _context;
public UserRepository(StudentSchedulingEntities context)
{
if (context == null)
throw new ArgumentNullException("context");
_context = context;
}
public IEnumerable<User> GetUsers()
{
return _context.Users.ToList();
}
public User GetUserByID(int id)
{
return _context.Users.Find(id);
}
public void InsertStudent(User user)
{
_context.Users.Add(user);
}
public void DeleteStudent(int userID)
{
User usr = _context.Users.Find(userID);
_context.Users.Remove(usr);
}
public void UpdateStudent(User user)
{
_context.Entry(user).State = EntityState.Modified;
}
public void Save() {
_context.SaveChanges();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_context != null)
{
_context.Dispose();
_context = null;
}
}
}
}
My IRepository looks like this:
public interface IUserRepository : IDisposable
{
IEnumerable<User> GetUsers();
User GetUserByID(int userID);
void InsertStudent(User user);
void DeleteStudent(int userID);
void UpdateStudent(User user);
void Save();
}
I want to avoid doing this again in the service layer. Do I need the Repository Class or should I just implement the Service Layer in replacement of the Repository?
Your service layer won't need any repository implementations, it will simply use a repository to lookup a user, add/edit/delete a user, etc.
Now, if I can offer a bit of opinion, I'd recommend going with a generic repository. That way, if you need to make new repositories it is really simple. We use nopCommerce, and they use the following code:
public partial interface IRepository<T> where T : BaseEntity
{
T GetById(object id);
void Insert(T entity);
void Update(T entity);
void Delete(T entity);
IQueryable<T> Table { get; }
}
And since it use Entity Framework, this is the implementation:
/// <summary>
/// Entity Framework repository
/// </summary>
public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
{
private readonly IDbContext _context;
private IDbSet<T> _entities;
/// <summary>
/// Ctor
/// </summary>
/// <param name="context">Object context</param>
public EfRepository(IDbContext context)
{
this._context = context;
}
public T GetById(object id)
{
return this.Entities.Find(id);
}
public void Insert(T entity)
{
try
{
if (entity == null)
throw new ArgumentNullException("entity");
this.Entities.Add(entity);
this._context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
var msg = string.Empty;
foreach (var validationErrors in dbEx.EntityValidationErrors)
foreach (var validationError in validationErrors.ValidationErrors)
msg += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;
var fail = new Exception(msg, dbEx);
//Debug.WriteLine(fail.Message, fail);
throw fail;
}
}
public void Update(T entity)
{
try
{
if (entity == null)
throw new ArgumentNullException("entity");
this._context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
var msg = string.Empty;
foreach (var validationErrors in dbEx.EntityValidationErrors)
foreach (var validationError in validationErrors.ValidationErrors)
msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
var fail = new Exception(msg, dbEx);
//Debug.WriteLine(fail.Message, fail);
throw fail;
}
}
public void Delete(T entity)
{
try
{
if (entity == null)
throw new ArgumentNullException("entity");
this.Entities.Remove(entity);
this._context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
var msg = string.Empty;
foreach (var validationErrors in dbEx.EntityValidationErrors)
foreach (var validationError in validationErrors.ValidationErrors)
msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
var fail = new Exception(msg, dbEx);
//Debug.WriteLine(fail.Message, fail);
throw fail;
}
}
public virtual IQueryable<T> Table
{
get
{
return this.Entities;
}
}
private IDbSet<T> Entities
{
get
{
if (_entities == null)
_entities = _context.Set<T>();
return _entities;
}
}
//TODO implement IDisposable interface
}
Now it would be as simple as IRepository<User> or IRepository<Whatever>.
Definitely no to redundant code :-) When you say:
My current structure is Controller -> Repository ->
Is Controller inheriting from Repository? You don't want that either. The repository layer typically interfaces to storage (XML, database, file system, etc) and maps to repository friendly classes. Another layer manages the mapping of the repository layer to your native business/service classes.

Resources