Hi
Right I am having major issues with managing my connection and keeping it stable with all the different things its doing.
Right I have three diffferent problems I am not sure what you would want me to post in terms of current code, so if you need anything let me know and I will post it.
The situations are:
1, All my files are stored in a DB, to return them the url goes to a controller theres an id in the url which is picked up and theres a database request which returned the info and the controller turns it to a file and sends it to the client. Now when I
use
builder.Register(c => new MyContext()).As<IUnitOfWork>().ExternallyOwned();
It works without issue, however when I then try and do I get errors like
Violation of PRIMARY KEY constraint 'PK_dbo.StockOptionParentTitle'. Cannot insert duplicate key in object 'dbo.StockOptionParentTitle'. The duplicate key value is (1, 1).
2, However when I use
builder.Register(c => new MyContext()).As<IUnitOfWork>().SingleInstance();
The first image on the page will load, however the next one will have the error:
InnerException = {"There is already an open DataReader associated with this Command which must be closed first."}
However I don’t have any problem inserting anything.
I think I have missed and therefore I am not managing IDisposal properly but where do i start:
My unit of work is:
public interface IUnitOfWork : IDisposable { void Save(); }
My repository looks like this
public partial class BaseRepository<T> : IBaseRepository<T> where T : BaseEntity { #region Fields /// <summary> /// Object context /// </summary> protected readonly MyContext _context; protected DbSet<T> _entities; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="context">Object context</param> public BaseRepository(IUnitOfWork unitOfWork) { if (unitOfWork == null) throw new ArgumentNullException("unitOfWork"); _context = unitOfWork as MyContext; this._entities = _context.Set<T>(); } #endregion #region Methods public virtual T GetById(object id) { return _entities.Find(id); } public virtual IEnumerable<T> GetAll() { return _entities.ToList(); } public virtual void Insert(T entity) { if (entity == null) throw new ArgumentNullException("entity"); try { this._entities.Add(entity); this._context.SaveChanges(); } catch (DbEntityValidationException dbEx) { foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } } } public virtual 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 virtual void Delete(T entity) { if (entity == null) throw new ArgumentNullException("entity"); //if (!this._context.IsAttached(entity)) // this._entities.Attach(entity); //this._context.DeleteObject(entity); //this._context.SaveChanges(); } #endregion #region Porperties public virtual IQueryable<T> Table { get { return this._entities; } } public virtual void Save() { try { this._context.SaveChanges(); } catch { //ToDo } } #endregion }
am I missing something?
Hi,
This issue is more related to EF with Autofac.
Please try to use InstancePerLifetimeScope.
There are some link that can benefit you:
# DbContext has been disposed and autofac
http://stackoverflow.com/questions/14919543/dbcontext-has-been-disposed-and-autofac
# Generic Repository and Unit of Work Pattern, Entity Framework, Unit Testing, Autofac IoC Container and ASP.NET MVC
http://techbrij.com/autofac-ioc-container-asp-net-mvc-di
Best Regards
Starain
Thanks for the info, I am trying the second example, on that example there is the following code:
public class EFModule : Autofac.Module { protected override void Load(ContainerBuilder builder) { builder.RegisterModule(new RepositoryModule()); builder.RegisterType(typeof(SampleArchContext)).As(typeof(DbContext)).InstancePerLifetimeScope(); builder.RegisterType(typeof(UnitOfWork)).As(typeof(IUnitOfWork)).InstancePerRequest(); } }
I get the error below on InstancePerRequest();
Error 1 'Autofac.Builder.IRegistrationBuilder<object,Autofac.Builder.ConcreteReflectionActivatorData,Autofac.Builder.SingleRegistrationStyle>' does not contain a definition for 'InstancePerRequest' and no extension method 'InstancePerRequest' accepting a first argument of type 'Autofac.Builder.IRegistrationBuilder<object,Autofac.Builder.ConcreteReflectionActivatorData,Autofac.Builder.SingleRegistrationStyle>' could be found (are you missing a using directive or an assembly reference?) C:UsersDocumentsVisual Studio 2012ProjectsNew Repository TestWeb.Admin.UIApp_StartEFDIModule.cs 19 78 Web.Admin.UI
Any suggestions would be appriciated.
Hi,
Could you share the project on the OneDrive?
Regards
Sure but I would prefer not to put a link on here
Hi,
You could create a simple project with some logic (Dependency injection) and share it.
Regards
I removed IQueryable from the service layer, so now its contained in the repository layer and all is working.
Thanks for the info