Dbcontext has been disposed when using "using Statement" - c#

Error message:
The operation cannot be completed because the dbcontext has been disposed.
Can somebody explain why and where my DbContext is getting disposed while I perform the update?
Context file:
using System.Data.Entity;
namespace OnlineTest
{
internal class OnlineTestContext : DbContext
{
private OnlineTestContext() : base("name=OnlineTest")
{
}
private static OnlineTestContext _instance;
public static OnlineTestContext GetInstance
{
get
{
if (_instance == null)
{
_instance = new OnlineTestContext();
}
return _instance;
}
}
public DbSet<User> Users { get; set; }
}
}
Business logic:
public int UpdateUser(User user)
{
user.ModifiedOn = DateTime.Now;
using (var context = OnlineTestContext.GetInstance)
{
context.Entry(user).State = EntityState.Modified;
return context.SaveChanges();
}
}
public User GetUserByEmailId(string emailId)
{
using (var context = OnlineTestContext.GetInstance)
{
return context.Users.First(u => u.EmailId == emailId);
}
}
Unit test:
[TestMethod]
public void UpdateUserUnitTest()
{
User user = onlineTestBusinessLogic.GetUserByEmailId("test#test");
user.PhoneNumber = "+91 1234567890";
int changes = onlineTestBusinessLogic.UpdateUser(user);
User Modifieduser = onlineTestBusinessLogic.GetUserByEmailId("test#test");
Assert.AreEqual(Modifieduser.PhoneNumber, "+91 0987654321");
}
Thank you.

It is disposed by the second time you call a method on a repository. A timeline is like that:
GetUserByEmailId is called, _instance is null, so it is initialized
GetUserByEmailId is completed, and context is disposed. But the object still exists in _instance field
UpdateUser is called, _instance is not null, so the old context is returned in using
context.SaveChanges is called, but since this object of context is already disposed, the exception is thrown
This is generally a good idea to avoid caching db context like this. Basic rule of thumb is "one context object per unit of work". You can find some more information about why is it so in this thread (starring Jon Skeet!).

The using keyword is you specifically saying "when the scope closes, call .Dispose() on the object I passed in". Which is not what you want, because you want to re-use the object over and over.
Remove the using and you will get stop getting this issue. e.g.
var context = OnlineTestContext.GetInstance;
context.Entry(user).State = EntityState.Modified;
return context.SaveChanges();

Related

C# Conditionally disposing of Entity Framework DbContext only when needed

I'm trying to make my code be intelligent enough to only open and dispose of an Entity Framework DBcontext if it's only needed within the Current execution lifetime of the method in question.
Basically, if a real context is being passed into the method then I do Not want to dispose of it.
However, if it's only needed for the Current execution lifetime of the method in question then it will disposed in the finally block
public int UpSertCompanyStockInfo( Guid companyId, string companyName, float stockPrice, float peRatio, CommunicationEngineDatabase context)
{
bool isContextOnlyCreatedForCurrentMethodExecutionRun = false;
if (context == null)
{
isContextOnlyCreatedForCurrentMethodExecutionRun = true;
context = new CommunicationEngineDatabase();
}
try
{
CompanyStockInfo companyStockInfo = new CompanyStockInfo();
companyStockInfo.CompanyName = companyName;
companyStockInfo.StockPrice = stockPrice;
context.CompanyStockInfoTable.Add(companyStockInfo);
context.SaveChanges();
}
catch (Exception _ex)
{
}
finally
{
if (isContextOnlyCreatedForCurrentMethodExecutionRun == true && context != null)
{
((IDisposable)context).Dispose();
}
}
return 0;
}
The problem is that I feel the aforementioned code is too much in terms of lines of code. Could someone please tell me how to shorten it( maybe even do it with the using statement)?
You can encapsulate the logic inside a helper disposable (so you can utilize using) class (even struct) like this:
class DbContextScope : IDisposable
{
public static DbContextScope Open<TContext>(ref TContext context) where TContext : DbContext, new()
=> context != null ? NullScope : new DbContextScope(context = new TContext());
static readonly DbContextScope NullScope = new DbContextScope(null);
private DbContextScope(DbContext context) => this.context = context;
readonly DbContext context;
public void Dispose() => context?.Dispose();
}
And the usage with your sample would be:
public int UpSertCompanyStockInfo( Guid companyId, string companyName, float stockPrice, float peRatio, CommunicationEngineDatabase context)
{
using (DbContextScope.Open(ref context))
{
CompanyStockInfo companyStockInfo = new CompanyStockInfo();
companyStockInfo.CompanyName = companyName;
companyStockInfo.StockPrice = stockPrice;
context.CompanyStockInfoTable.Add(companyStockInfo);
context.SaveChanges();
}
return 0;
}

Is disposed called when creating a reference to an existing object?

I have a class with a method performing some database actions.
I want to allow an existing (open) context to be sent in the method call to be used for the database access.
However if a context is not sent, I create a new one.
I just want to make sure the object is not disposed if included in the method call.
Is the object disposed when a using-scope is used in the called method?
// DbService class
class DbService
{
private void SomeDbAction(SomeDbContextObject backendContext = null)
{
using (var context = backendContext ?? CreateNewContextObject())
{
// Some actions using the context
}
}
}
// Call from another class
class Temp
{
void DoSomeThing()
{
var existingContext = new SomeDbContextObject();
dbService.SomeDbAction(existingContext);
// Is dbService disposed here?
UseContextForSomethingElse(existingContext);
}
}
// Is dbService disposed here?
Yes, it is disposed. This is a case where optional arguments work against you - better to have two specific overloads:
class DbService
{
public void SomeDbAction(SomeDbContextObject backendContext)
{
// Some actions using the context
}
public void SomeDbAction()
{
using (var context = CreateNewContextObject())
{
SomeDbAction(context);
}
}
}
You should not dispose of the backendContext object if it has been passed in, but should do so if you created it in the method:
private void CoreSomeDbAction(SomeDbContextObject backendContext) {
//TODO: Some actions using the context
}
private void SomeDbAction(SomeDbContextObject backendContext = null) {
if (null == backendContext) {
// created context should be disposed
using (SomeDbContextObject context = new SomeDbContextObject(...)) {
CoreSomeDbAction(context);
}
}
else
CoreSomeDbAction(backendContext); // passed context should be prevent intact
}

How can Ninject be configured to always deactivate pooled references?

We're using a library that uses pooled objects (ServiceStack.Redis's PooledRedisClientManager). Objects are created and reused for multiple web requests. However, Dispose should be called after each use to release the object back into the pool.
By default, Ninject only deactivates an object reference if it has not been deactivated before.
What happens is that the pool instantiates an object and marks it as active. Ninject then runs the activation pipeline. At the end of the request (a web request), Ninject runs the deactivation pipeline which calls Dispose (and thus the pool marks the object as inactive). The next request: the first pooled instance is used and the pool marks it as active. However, at the end of the request, Ninject does not run its deactivation pipeline because the ActivationCache has already marked this instance as deactivated (this is in the Pipeline).
Here's a simple sample that we've added in a new MVC project to demonstrate this problem:
public interface IFooFactory
{
IFooClient GetClient();
void DisposeClient(FooClient client);
}
public class PooledFooClientFactory : IFooFactory
{
private readonly List<FooClient> pool = new List<FooClient>();
public IFooClient GetClient()
{
lock (pool)
{
var client = pool.SingleOrDefault(c => !c.Active);
if (client == null)
{
client = new FooClient(pool.Count + 1);
client.Factory = this;
pool.Add(client);
}
client.Active = true;
return client;
}
}
public void DisposeClient(FooClient client)
{
client.Active = false;
}
}
public interface IFooClient
{
void Use();
}
public class FooClient : IFooClient, IDisposable
{
internal IFooFactory Factory { get; set; }
internal bool Active { get; set; }
internal int Id { get; private set; }
public FooClient(int id)
{
this.Id = id;
}
public void Dispose()
{
if (Factory != null)
{
Factory.DisposeClient(this);
}
}
public void Use()
{
Console.WriteLine("Using...");
}
}
public class HomeController : Controller
{
private IFooClient foo;
public HomeController(IFooClient foo)
{
this.foo = foo;
}
public ActionResult Index()
{
foo.Use();
return View();
}
public ActionResult About()
{
return View();
}
}
// In the Ninject configuration (NinjectWebCommon.cs)
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IFooFactory>()
.To<PooledFooClientFactory>()
.InSingletonScope();
kernel.Bind<IFooClient>()
.ToMethod(ctx => ctx.Kernel.Get<IFooFactory>().GetClient())
.InRequestScope();
}
The solutions that we've come up with thus far are:
Mark these objects as InTransientScope() and use other deactivation mechanism (like an MVC ActionFilter to dispose of the object after each request). We'd lose the benefits of Ninject's deactivation process and require an indirect approach to disposing of the object.
Write a custom IActivationCache that checks the pool to see if the object is active. Here's what I've written so far, but I'd like some one else's eyes to see how robust it is:
public class PooledFooClientActivationCache : DisposableObject, IActivationCache, INinjectComponent, IDisposable, IPruneable
{
private readonly ActivationCache realCache;
public PooledFooClientActivationCache(ICachePruner cachePruner)
{
realCache = new ActivationCache(cachePruner);
}
public void AddActivatedInstance(object instance)
{
realCache.AddActivatedInstance(instance);
}
public void AddDeactivatedInstance(object instance)
{
realCache.AddDeactivatedInstance(instance);
}
public void Clear()
{
realCache.Clear();
}
public bool IsActivated(object instance)
{
lock (realCache)
{
var fooClient = instance as FooClient;
if (fooClient != null) return fooClient.Active;
return realCache.IsActivated(instance);
}
}
public bool IsDeactivated(object instance)
{
lock (realCache)
{
var fooClient = instance as FooClient;
if (fooClient != null) return !fooClient.Active;
return realCache.IsDeactivated(instance);
}
}
public Ninject.INinjectSettings Settings
{
get
{
return realCache.Settings;
}
set
{
realCache.Settings = value;
}
}
public void Prune()
{
realCache.Prune();
}
}
// Wire it up:
kernel.Components.RemoveAll<IActivationCache>();
kernel.Components.Add<IActivationCache, PooledFooClientActivationCache>();
Specifically for ServiceStack.Redis's: use the PooledRedisClientManager.DisposablePooledClient<RedisClient> wrapper so we always get a new object instance. Then let the client object become transient since the wrapper takes care of disposing it. This approach does not tackle the broader concept of pooled objects with Ninject and only fixes it for ServiceStack.Redis.
var clientManager = new PooledRedisClientManager();
kernel.Bind<PooledRedisClientManager.DisposablePooledClient<RedisClient>>()
.ToMethod(ctx => clientManager.GetDisposableClient<RedisClient>())
.InRequestScope();
kernel.Bind<IRedisClient>()
.ToMethod(ctx => ctx.Kernel.Get<PooledRedisClientManager.DisposablePooledClient<RedisClient>>().Client)
.InTransientScope();
Is one of these approaches more appropriate than the other?
I have not use Redis so far so I can not tell you how to do it correctly. But I can give you some input in general:
Disposing is not the only thing that is done by the ActivationPipeline. (E.g. it also does property/method injection and excuting activation/deactivation actions.) By using a custom activation cache that returns false even though it has been activated before will cause that these other actions are executed again (E.g. resulting in property injection done again.)

Exception deleting using Entity Framework (C#)

I have a problem with some simple code, I'm refactoring some existing code from LINQ to SQL to the Entity Framework. I'm testing my saves and deletes, and the delete is really bugging me:
[TestMethod]
public void TestSaveDelete()
{
ObjectFactory.Initialize(x =>
{
x.For<IArticleCommentRepository>().Use<ArticleCommentRepository>();
});
PLArticleComment plac = new PLArticleComment();
plac.Created = DateTime.Now;
plac.Email = "myemail";
plac.Name = "myName";
plac.Text = "myText";
plac.Title = "myTitle";
IArticleCommentRepository acrep = ObjectFactory.GetInstance<IArticleCommentRepository>();
try
{
PortalLandEntities ple = new PortalLandEntities();
int count = ple.PLArticleComment.Count();
acrep.Save(plac);
Assert.AreEqual(ple.PLArticleComment.Count(), count + 1);
//PLArticleComment newPlac = ple.PLArticleComment.First(m => m.Id == plac.Id);
//ple.Attach(newPlac);
acrep.Delete(plac);
Assert.AreEqual(ple.PLArticleComment.Count(), count + 1);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Every time i try to run this code, I get an exception in the delete statement, telling me that its not contained within the current ObjectStateManager.Please note that both my Save and delete looks like this:
public void Delete(PLCore.Model.PLArticleComment comment)
{
using (PortalLandEntities ple = Connection.GetEntityConnection())
{
ple.DeleteObject(comment);
ple.SaveChanges();
}
}
public void Save(PLCore.Model.PLArticleComment comment)
{
using (PortalLandEntities ple = Connection.GetEntityConnection())
{
ple.AddToPLArticleComment(comment);
ple.SaveChanges();
}
}
and the connection thingy:
public class Connection
{
public static PortalLandEntities GetEntityConnection()
{
return new PortalLandEntities();
}
}
Any ideas on what i could do to make it work?
You cannot load an entity from one ObjectContext (in your case, an ObjectContext is an instance of PortalLandEntities) and then delete it from another ObjectContext, unless you detach it from the first and attach it to the second. Your life will be much, much simpler if you use only one ObjectContext at a time. If you cannot do that, you must manually Detach and then Attach first, all the while keeping track of which entities are connected to which ObjectContext.
How to use DI with your Connection : make it non-static.
public class Connection
{
private PortalLandEntities _entities;
public PortalLandEntities GetEntityConnection()
{
return _entities;
}
public Connection(PortalLandEntities entities)
{
this._entities = entities;
}
}
Then use a DI container per request. Most people do this via a controller factory.

Object Context, Repositories and Transactions

I was wondering what the best way to use transations with the entity framework.
Say I have three repositories:
Repo1(ObjectContext context)
Repo2(ObjectContext context)
Repo3(ObjectContext context)
and a service object that takes the three repositories:
Service(Repo1 repo1,Repo2 repo2, Repo3 repo3)
Serive.CreateNewObject <- calls repo1, repo2, repo3 to do stuff.
So when I create the service I create three repositories first and pass them down, each repositry takes a object context so my code looks something like this:
MyObjectContext context = new MyObjectContext();
Repo1 repo = new Repo1(context);
// etc
Now I have a controller class that is responsible for calling different services and compants of my application, showing the right forms etc. Now what I want to be able to do is wrap everything that happens in one of the controller methods in a transaction so that if some thing goes wrong I can rollback back.
The controller takes a few different Service objects, but doesn't know anything about the object context.
My questions are:
Should the context be passed in to the service layer also.
How do I implement a transaction in the controller so that anything that happens in the service
layers arn't commited untill everything has passed.
Sorry if it's a bit hard to understand..
Why doesn't your controller know about the ObjectContext?
This is where I would put it. Check out - http://msdn.microsoft.com/en-us/magazine/dd882510.aspx - here the Command is what will commit/rollback the UnitOfWork(ObjectContext).
If you don't want to have your Controller know exactly about the EF (good design) then you want to abstract your ObjectContext into an interface similar to the approach in the above link.
How about using a custom TransactionScope, one that commits when all of your services have committed?
public class TransactionScope : Scope<IDbTransaction>
{
public TransactionScope()
{
InitialiseScope(ConnectionScope.CurrentKey);
}
protected override IDbTransaction CreateItem()
{
return ConnectionScope.Current.BeginTransaction();
}
public void Commit()
{
if (CurrentScopeItem.UserCount == 1)
{
TransactionScope.Current.Commit();
}
}
}
So the transaction is only committed when the UserCount is 1, meaning the last service has committed.
The scope classes are (shame we can't do attachements...):
public abstract class Scope<T> : IDisposable
where T : IDisposable
{
private bool disposed = false;
[ThreadStatic]
private static Stack<ScopeItem<T>> stack = null;
public static T Current
{
get { return stack.Peek().Item; }
}
internal static string CurrentKey
{
get { return stack.Peek().Key; }
}
protected internal ScopeItem<T> CurrentScopeItem
{
get { return stack.Peek(); }
}
protected void InitialiseScope(string key)
{
if (stack == null)
{
stack = new Stack<ScopeItem<T>>();
}
// Only create a new item on the stack if this
// is different to the current ambient item
if (stack.Count == 0 || stack.Peek().Key != key)
{
stack.Push(new ScopeItem<T>(1, CreateItem(), key));
}
else
{
stack.Peek().UserCount++;
}
}
protected abstract T CreateItem();
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// If there are no users for the current item
// in the stack, pop it
if (stack.Peek().UserCount == 1)
{
stack.Pop().Item.Dispose();
}
else
{
stack.Peek().UserCount--;
}
}
// There are no unmanaged resources to release, but
// if we add them, they need to be released here.
}
disposed = true;
}
}
public class ScopeItem<T> where T : IDisposable
{
private int userCount;
private T item;
private string key;
public ScopeItem(int userCount, T item, string key)
{
this.userCount = userCount;
this.item = item;
this.key = key;
}
public int UserCount
{
get { return this.userCount; }
set { this.userCount = value; }
}
public T Item
{
get { return this.item; }
set { this.item = value; }
}
public string Key
{
get { return this.key; }
set { this.key = value; }
}
}
public class ConnectionScope : Scope<IDbConnection>
{
private readonly string connectionString = "";
private readonly string providerName = "";
public ConnectionScope(string connectionString, string providerName)
{
this.connectionString = connectionString;
this.providerName = providerName;
InitialiseScope(string.Format("{0}:{1}", connectionString, providerName));
}
public ConnectionScope(IConnectionDetailsProvider connectionDetails)
: this(connectionDetails.ConnectionString, connectionDetails.ConnectionProvider)
{
}
protected override IDbConnection CreateItem()
{
IDbConnection connection = DbProviderFactories.GetFactory(providerName).CreateConnection();
connection.ConnectionString = connectionString;
connection.Open();
return connection;
}
}
Wrap the operation in a TransactionScope.
You might want to implement the transaction model used by the Workflow Foundation. It basically has an interface that all "components" implement. After each does the main work successfully, then the host calls the "commit" method on each. If one failed, it calls the "rollback" method.

Categories

Resources