EF6 DbContext lifecycle issue - entity-framework

I've decided to architect my solution without repositories and unit of work (given that EF is itself a repository/uow so why abstract an abstraction). So I have a Service/Business Logic layer which will call EF directly. My service has a number of methods (Create, Update, Delete) which call _context.SaveChanges() and I am injecting the DbContext in the constructor.
However if I call multiple methods using the same service instance and one fails, all further service methods will also fail. For example
var svc = new PersonService();
var person = new Person{ Name = "Angie" };
svc.Create(person);
svc.Delete(56); //delete person with Id 50
Lets assume Create throws an exception on SaveChanges for some reason. When I call Delete, there is still a faulty Person object in my context, so when Delete method calls SaveChanges it will throw the same exception.
Of course I can get around this by always instantiating a new PersonService in my calling code but this just screams WRONG.
This leads me to using a new context for each service method, which will mean method injection instead of constructor injection which I was hoping to avoid.
I've considered going back to repository/uow but it seems that this just moves the problem one layer deeper.
Is method injection of my context the right way to go or am I missing something here?
Thanks

Related

WCF with IOperationInvoker using Entity and Ninject

I have a WCF Service from which I need to log the calls to its methods. For this, I used this solution to be able to track the calls and call my internal audit service, which uses Entity 5.1 and injects the services/repositories/DbContext using Ninject.
My Invoke method looks like this:
public object Invoke(object instance, object[] inputs, out object[] outputs)
{
var methodParams = (instance).GetType().GetMethod(_operationName).GetParameters();
var parameters = new Dictionary<string, object>();
for (var index = 0; index < inputs.Length; index++)
parameters.Add(methodParams[index].Name, inputs[index]);
_auditService.TrackFilterParametersValues(_operation.Parent.Type.FullName, _operationName, _operation.Action, parameters);
return _baseInvoker.Invoke(instance, inputs, out outputs);
}
In my Ninject module I have the internal stuff registered like this:
Bind<IAuditService>().To<AuditeService>().InRequestScope();
Bind(typeof(IRepository<>)).To(typeof(Repository<>)).InRequestScope();
Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
Bind<DbContext>().To<MyEntities>().InRequestScope();
Problem comes up when, inside the Repository, I call the dbContext to add the new Audit object like this:
_dbContext.Set<T>().Add(entity);
It errors out claiming that the DbContext has been disposed.
What would be the correct way of registering the DbContext on a WCF Service so it gets registered for an IOperationInvoker??
I have to mention that I have all this declaration the same for the main site I'm feeding up with this backend in MVC4 and it works perfectly (no WCF there). So I'm pretty sure something is needed to be corrected for the WCF lifetime cycle, but not so sure about what.
I found the reason of why this was behaving so nasty: in the chain formed by the IOperationInvoker, IOperationBehavior and IServiceBehavior, I was injecting the AuditService by the constructor of the first 2 of them, but in the latest (IServiceBehavior), since I was decorating the WCF class with it and couldn't overload the constructor, I was using the DependencyResolver to obtain the AuditService with a property like this:
public IAuditService AuditService
{
get { return DependencyResolver.Current.GetService<IAuditService>();
}
Then, when I started to debug, I noticed that the constructors were called when the WCF Test Client was querying the WCF for the WSDL data, but the Invoke method was never called because no web method was being invoked. So the AuditService instance (and DbContext) was all fine during the calls of the constructors, but by the time of invoking a web method and calling the Invoke method of the IOperationInvoker, the DbContext was already disposed long time ago.
My workaround for this was to delete all the references to the AuditService from all constructors and move the property with the DependencyResolver from the ServiceBehavior to the IOperationInvoker implementation. Once I did this, the AuditService is called right when it's needed, never before, and its DbContext is never disposed.
If MyEntities inherits from DbContext, then this should work:
Bind(typeof(DbContext)).To(typeof(MyEntities)).InRequestScope();

Entity Framework 5 Unit of Work pattern - where should I call SaveChanges?

Apologies, in advance, if this seems like a duplicate question. This question was the closest I could find, but it doesn't really solve the issues I am facing.
I'm using Entity Framework 5 in an ASP.NET MVC4 application and attempting to implement the Unit of Work pattern.
My unit of work class implements IDisposable and contains a single instance of my DbContext-derived object context class, as well as a number of repositories, each of which derives from a generic base repository class that exposes all the usual repository functionality.
For each HTTP request, Ninject creates a single instance of the Unit of Work class and injects it into the controllers, automatically disposing it when the request is complete.
Since EF5 abstracts away the data storage and Ninject manages the lifetime of the object context, it seems like the perfect way for consuming code to access in-memory entity objects without the need to explcitly manage their persistence. In other words, for optimum separation of concerns, I envisage my controller action methods being able to use and modify repository data without the need to explicitly call SaveChanges afterwards.
My first (naiive) attempt to implement this idea employed a call to SaveChanges within every repository base-class method that modified data. Of course, I soon realized that this is neither performance optimized (especially when making multiple successive calls to the same method), nor does it accommodate situations where an action method directly modifies a property of an object retrieved from a repository.
So, I evolved my design to eliminate these premature calls to SaveChanges and replace them with a single call when the Unit of Work instance is disposed. This seemed like the cleanest implementation of the Unit of Work pattern in MVC, since a unit of work is naturally scoped to a request.
Unfortunately, after building this concept, I discovered its fatal flaw - the fact that objects added to or deleted from a DbContext are not reflected, even locally, until SaveChanges has been called.
So, what are your thoughts on the idea that consuming code should be able to use objects without explicitly persisting them? And, if this idea seems valid, what's the best way to achieve it with EF5?
Many thanks for your suggestions,
Tim
UPDATE: Based on #Wahid's response, I am adding below some test code that shows some of the situations in which it becomes essential for the consuming code to explicitly call SaveChanges:
var unitOfWork = _kernel.Get<IUnitOfWork>();
var terms = unitOfWork.Terms.Entities;
// Purge the table so as to start with a known state
foreach (var term in terms)
{
terms.Remove(term);
}
unitOfWork.SaveChanges();
Assert.AreEqual(0, terms.Count());
// Verify that additions are not even reflected locally until committed.
var created = new Term { Pattern = "Test" };
terms.Add(created);
Assert.AreEqual(0, terms.Count());
// Verify that additions are reflected locally once committed.
unitOfWork.SaveChanges();
Assert.AreEqual(1, terms.Count());
// Verify that property modifications to entities are reflected locally immediately
created.Pattern = "Test2";
var another = terms.Single(term => term.Id == created.Id);
Assert.AreEqual("Test2", another.Pattern);
Assert.True(ReferenceEquals(created, another));
// Verify that queries against property changes fail until committed
Assert.IsNull(terms.FirstOrDefault(term => term.Pattern == "Test2"));
// Verify that queries against property changes work once committed
unitOfWork.SaveChanges();
Assert.NotNull(terms.FirstOrDefault(term => term.Pattern == "Test2"));
// Verify that deletions are not even reflected locally until committed.
terms.Remove(created);
Assert.AreEqual(1, terms.Count());
// Verify that additions are reflected locally once committed.
unitOfWork.SaveChanges();
Assert.AreEqual(0, terms.Count());
First of all SaveChanges should NOT be ever in the repositories at all. Because that's leads you to lose the benefit of UnitOfWork.
Second you need to make a special method to save changes in the UnitOfWork.
And if you want to call this method automatically then you may fine some other solution like ActionFilter or maybe by making all your Controllers inherits from BaseController class and handle the SaveChanges in it.
Anyway the UnitOfWork should always have SaveChanges method.

Creating new entities while enabling injection

I have a method on a stateless session bean which creates a new instance of an entity and persists it. You might normally use new MyEntity() to create the object but I would like injection to populate some of the properties of the entity for me.
I got partial success using
#Inject
#New
private MyEntity myNewEntity;
in the session bean and then using that instance in my method.
The problem I have now is that the second time the method is called, myNewEntity isn't a new object, its the same object as the one created the first time. As a result I'm getting
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '9' for key 'PRIMARY'
Or at least that's why I think I'm getting this exception. Certainly if I use new MyEntity() I don't get the exception but my injection doesn't happen.
Am I on the wrong track? How can I create a new local entity object while enabling injection?
Any help would be great!
First of all - I have serious doubts that it's a good idea to use CDI to control the lifecycle of a Entity. See this quote from the documentation (here):
According to this definition, JPA
entities are technically managed
beans. However, entities have their
own special lifecycle, state and
identity model and are usually
instantiated by JPA or using new.
Therefore we don't recommend directly
injecting an entity class. We
especially recommend against assigning
a scope other than #Dependent to an
entity class, since JPA is not able to
persist injected CDI proxies.
What you should do to create new instances of entities is adding a layer of indirection, either with #Produces or #Unwraps (Seam Solder, if you need it to be truly stateless), and thereby making sure that you code explicitly calls new.
I think I have a working solution now which seems okay, though I'm not quite sure why it works so I welcome your feedback on a better solution. I am now injecting a DAO-style bean into my stateless session bean:
#Stateless
public class PhoneService {
#Inject
protected ProblemReports problemReports;
An injecting my entity into the ProblemReports bean:
public class ProblemReports {
#Inject
#New
private ProblemReport newProblemReport;
I assume that ProblemReports defaults to #Dependant scope which as I understand it should be the same as the stateless session bean which containts it. I could understand this if the scope of ProblemReports was shorter, causing a new instance of ProblemReport to be created when the new ProblemReports is created; but it isn't.
Is this just an example of EJB and CDI not playing well together?

Entity Framework Generic Repository Context

I am building an ASP.NET 4.0 MVC 2 app with a generic repository based on this blog post.
I'm not sure how to deal with the lifetime of ObjectContext -- here is a typical method from my repository class:
public T GetSingle<T>(Func<T, bool> predicate) where T : class
{
using (MyDbEntities dbEntities = new MyDbEntities())
{
return dbEntities.CreateObjectSet<T>().Single(predicate);
}
}
MyDbEntities is the ObjectContext generated by Entity Framework 4.
Is it ok to call .CreateObjectSet() and create/dispose MyDbEntities per every HTTP request? If not, how can I preserve this object?
If another method returns an IEnumerable<MyObject> using similar code, will this cause undefined behavior if I try to perform CRUD operations outside the scope of that method?
Yes, it is ok to create a new object context on each request (and in turn a call to CreateObjectSet). In fact, it's preferred. And like any object that implements IDisposable, you should be a good citizen and dispose it (which you're code above is doing). Some people use IoC to control the lifetime of their object context scoped to the http request but either way, it's short lived.
For the second part of your question, I think you're asking if another method performs a CRUD operation with a different instance of the data context (let me know if I'm misinterpreting). If that's the case, you'll need to attach it to the new data context that will perform the actual database update. This is a fine thing to do. Also, acceptable would be the use the Unit of Work pattern as well.

Entity Framework - How should I instance my "Entities" object

I'm a total newbie at Entity Framework and ASP.Net MVC, having learned mostly from tutorials, without having a deep understanding of either. (I do have experience on .Net 2.0, ADO.Net and WebForms)
My current doubt comes from the way I'm instancing my Entities objects.
Basically I'm doing this in my controllers:
public class PostsController : Controller {
private NorthWindEntities db = new NorthWindEntities();
public ActionResult Index() {
// Use the db object here, never explicitly Close/Dispose it
}
}
I'm doing it like this because I found it in some MSDN blog that seemed authoritative enough to me that I assumed this was a correct way.
However, I feel pretty un-easy about this. Although it saves me a lot of code, I'm used to doing:
using (NorthWindEntities db = new NorthWindEntities() {
}
In every single method that needs a connection, and if that method calls others that'll need it, it'll pass db as a parameter to them. This is how I did everything with my connection objects before Linq-to-SQL existed.
The other thing that makes me uneasy is that NorthWindEntities implements IDisposable, which by convention means I should be calling it's Dispose() method, and I'm not.
What do you think about this?
Is it correct to instance the Entities object as I'm doing? Should it take care of its connections by opening and closing them for each query?
Or should I be disposing it explicitly with a using() clause?
Thanks!
Controller itself implements IDisposable. So you can override Dispose and dispose of anything (like an object context) that you initialize when the controller is instantiated.
The controller only lives as long as a single request. So having a using inside an action and having one object context for the whole controller is exactly the same number of contexts: 1.
The big difference between these two methods is that the action will have completed before the view has rendered. So if you create your ObjectContext in a using statement inside the action, the ObjectContext will have been disposed before the view has rendered. So you better have read anything from the context that you need before the action completes. If the model you pass to the view is some lazy list like an IQueryable, you will have disposed the context before the view is rendered, causing an exception when the view tries to enumerate the IQueryable.
By contrast, if you initialize the ObjectContext when the Controller is initialized (or write lazy initialization code causing it to be initialized when the action is run) and dispose of the ObjectContext in the Controller.Dispose, then the context will still be around when the view is rendered. In this case, it is safe to pass an IQueryable to the view. The Controller will be disposed shortly after the view is rendered.
Finally, I'd be remiss if I didn't point out that it's probably a bad idea to have your Controller be aware of the Entity Framework at all. Look into using a separate assembly for your model and the repository pattern to have the controller talk to the model. A Google search will turn up quite a bit on this.
You are making a good point here. How long should the ObjectContext live? All patterns and practises books (like Dino Esposito's Microsoft-NET-Architecting-Applications) tell you that a DataContext must not live long, nor should it be cached.
I was just wondering why not having, in your case, a ControllerBase class (I'm not aware of the MVC implementation, so bear with me) where the ObjectContext gets initiated once for all controller. Especially think about the Identity Map Pattern, that's already implemented by Entity Framework. Even though you need to call another controller as your PostsController, it would still work with the same Context and improve performance as well.