Salve galera,
Criei um pequeno projeto para aplicar IoC utilizando o Unity da MS. Primeiramente sempre usei o conceito de UnitOfWork apenas instanciado ele em meus controllers, mas agora quero injetar eles.
Quando inicio a aplicação web ele lista corretamente as informações do banco, porem sempre que chamo o SaveChanges está dando o erro: {"The operation cannot be completed because the DbContext has been disposed."}
Não estou conseguindo achar o motivo disso, visto que o contexto está sendo injeto no UnitOfWork corretamente, se não ele nem conseguiria listar as informações do banco. Segue meu código.
Unity Config
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Mvc;
using MyMoney.DAL.Repositories;
using MyMoney.DAL.UnitOfWork;
using MyMoney.Domain.Interfaces.Repositories;
using System.Web.Mvc;
namespace MyMoney.DAL.Unity
{
public class Bootstrapper
{
public static IUnityContainer Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
return container;
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
container.RegisterType(typeof(ITransaction), typeof(TransactionRepository));
container.RegisterType<IUnitOfWork, UnitOfWork.UnitOfWork>(new ContainerControlledLifetimeManager());
return container;
}
}
}
UnitOfWork
using System;
using MyMoney.DAL.Context;
using MyMoney.Domain.Interfaces.Repositories;
namespace MyMoney.DAL.UnitOfWork
{
public class UnitOfWork : IUnitOfWork
{
private MyMoneyContext _context;
private ITransaction _transactionRepository;
public UnitOfWork(MyMoneyContext context, ITransaction transactionRepository)
{
this._context = context;
this._transactionRepository = transactionRepository;
}
public ITransaction TransactionRepository
{
get
{
return _transactionRepository;
}
}
public void Save()
{
_context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
Repositório
using MyMoney.DAL.Context;
using MyMoney.Domain.Entities;
using MyMoney.Domain.Interfaces.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
namespace MyMoney.DAL.Repositories
{
public class TransactionRepository : RepositoryBase<Transaction>, ITransaction
{
public TransactionRepository(MyMoneyContext db) : base(db)
{
}
public override IEnumerable<Transaction> GetAll(Guid userId)
{
return db.Transations.Where(x => x.UserId == userId).ToList();
}
public override void Add(Transaction transaction, Guid userId)
{
transaction.UserId = userId;
db.Transations.Add(transaction);
}
public override Transaction GetById(int id, Guid userId)
{
return db.Transations.Where(x => x.UserId == userId && x.Id == id).FirstOrDefault();
}
}
}
Controller
using AutoMapper;
using MyMoney.Domain.Entities;
using MyMoney.MVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using System.Data.Entity.Validation;
using System.Text;
using MyMoney.DAL.UnitOfWork;
namespace MyMoney.MVC.Controllers
{
public class TransactionsController : Controller
{
readonly IUnitOfWork _unitOfWork;
readonly Guid userId;
public TransactionsController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
userId = new Guid(System.Web.HttpContext.Current.User.Identity.GetUserId());
}
// GET: Transactions
public ActionResult Index()
{
return View();
}
public ActionResult TransactionList()
{
var tList = Mapper.Map<IEnumerable<Transaction>, IEnumerable<TransactionViewModel>>(_unitOfWork.TransactionRepository.GetAll(userId));
return this.PartialView("TransactionList", tList.ToList());
}
public PartialViewResult EditCreateForm(int id = 0)
{
TransactionViewModel viewModel = null;
if (id > 0)
{
var transaction = _unitOfWork.TransactionRepository.GetById(id, userId);
viewModel = Mapper.Map<Transaction, TransactionViewModel>(transaction);
}
return this.PartialView("EditCreate", viewModel);
}
[HttpPost]
public ActionResult EditCreate(TransactionViewModel viewModel)
{
try
{
if (viewModel.Id > 0)
{
var transactionDomain = Mapper.Map<TransactionViewModel, Transaction>(viewModel);
_unitOfWork.TransactionRepository.Update(transactionDomain);
_unitOfWork.Save();
return Json(0);
}
else
{
var transactionDomain = Mapper.Map<TransactionViewModel, Transaction>(viewModel);
_unitOfWork.TransactionRepository.Add(transactionDomain, userId);
_unitOfWork.Save();
return Json(0);
}
}
catch (Exception ex)
{
var msg = new StringBuilder();
if (ex is DbEntityValidationException)
{
var errors = ex as DbEntityValidationException;
foreach (var err in errors.EntityValidationErrors.SelectMany(x => x.ValidationErrors.Select(get => get.ErrorMessage)))
{
msg.AppendLine(err);
}
}
else
{
msg.AppendLine(ex.Message);
}
return Json(msg.ToString());
}
}
[HttpPost]
public ActionResult DeleteConfirmed(int id)
{
try
{
_unitOfWork.TransactionRepository.Remove(id);
_unitOfWork.Save();
return Json(0);
}
catch (Exception ex)
{
var msg = new StringBuilder();
if (ex is DbEntityValidationException)
{
var errors = ex as DbEntityValidationException;
foreach (var err in errors.EntityValidationErrors.SelectMany(x => x.ValidationErrors.Select(get => get.ErrorMessage)))
{
msg.AppendLine(err);
}
}
else
{
msg.AppendLine(ex.Message);
}
return Json(msg.ToString());
}
}
protected override void Dispose(bool disposing)
{
_unitOfWork.Dispose();
base.Dispose(disposing);
}
}
}
Context
using MyMoney.DAL.EntityCfg;
using MyMoney.Domain.Entities;
using System;
using System.Data.Entity;
using System.Linq;
namespace MyMoney.DAL.Context
{
public class MyMoneyContext : DbContext
{
public MyMoneyContext()
: base("MyMoney")
{
}
public DbSet<Transaction> Transations { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new TransactionConfig());
}
public override int SaveChanges()
{
foreach (var entry in ChangeTracker.Entries().Select(x => x))
{
if (entry.State == EntityState.Added)
{
entry.Property("Date").CurrentValue = DateTime.Now;
}
if (entry.State == EntityState.Modified)
{
entry.Property("Date").IsModified = false;
entry.Property("UserId").IsModified = false;
}
}
return base.SaveChanges();
}
}
}
Se precisarem de mais informação eu coloco aqui.
Grato pela ajuda desde já.