we are developing ASP.NET web application with cEF ode first. What/Where is the best possible place to create/dispose DBContext for a request? I have only a single context and am not using any DI containers. Currently i have multiple methods to call per request and each creates context of their own. How do i say, something like.. GetContextforRequest() and use it for the request and dispose it when request is processed?
Thanks in advance
What't your looking for in terms of having 1 context per request is a pretty good way to use contexts, in that you reduce the overhead of creating them. You can create new context on BeginRequest, and store it in HttpContext.Current.Items, and on EndRequest dispose of it.
You can then create a . GetContextforRequest() method to encapsulate the fetch from HttpContext.Current.Items
I would however suggest looking at using a DI container. most of them have helpers to aide with creating and disposing of objects per request.
Edit
The benefit of having a Context open for the duration of a Request is that you can take advantage of 1st level caching. This is where objects are cached for the lifetime of the Context. So say you have a table called User containing a bunch of Users, and you call context.Set().ToList() twice in the same request, the first call will fetch the data from the database, the second call will retrieve it from the 1st level cache.
Related
I am using a custom AuthAttribute to determine whether a user can access a controller and/or actions. The problem is I have to duplicate information and EFx connections in the attribute that already exist on the class that is being adorned.
My question is whether there is a way to access the fields on the adorned class from the custom AuthAttribute? I am trying to avoid having to re-architect the software in a way that would provide a single point of access since that would open up a different can of worms.
I believe I have found an answer that works. I welcome all comments on this solution.
Rather than have the attribute gain access to the properties and fields on the controller it adorns you can share values between them in a thread-safe way through the common HttpContext object. So if you are being extreme like I am and are trying to cut down on duplicate calls to your database in both the authattribute and the adorned controller action then pass the results forward. What that means is the authattribute will be called first and you can stash the retrieved values in the "Items" collection off the HttpContext object passed into the AuthorizeCore(..) method. You can then retrieve the same value in a THREAD-SAFE way through the HttpContext object in the controller.
example to save value within the AuthorizeCore(..) override of the AuthAttribute:
httpContext.Items.Add("fester", "bester");
example to retrieve value inside the subsequent call to the Controller/Action:
this.HttpContext.ApplicationInstance.Context.Items["fester"];
I have to warn you this is only a possible implementation that appears to work in simple testing. Personally it feels like a hack and there has to be a better way. I would also state this is in pursuit of a dubious performance benefit. It should cut down on the number of database and/or network calls by cache'ing retrieved data in the HttpContext so you don't have to repeat the calls in both the authattribute and the adorned Controller/Action. If you don't have a web site that gets a huge volume of calls then I would warn you against this.
I hope someone recommends something better on this page. I will keep an eye on how this works on my web site and let y'all know if it behaves and is truly thread-safe.
I want to save changes on backend also, so I want to subclass NSManagedContext, override save method and loop al the changed object and call the appropriate RESTFull service. But how can I get the changed / inserted objects?
UPDATE:
I found that with setIncludesPendingChanges I can get the changed objects, but I still need to set the entity name for NSFetchRequest. But I want to fetch all different type of entites. How?
I found here a more appropriate solution based on NSManagedObjectContextDidSaveNotification: How to sync CoreData and a REST web service asynchronously and the same time properly propagate any REST errors into the UI
After using EFProfiler (absolutely fantastic tool BTW!) for profiling a few of our Entity Framework applications, it seems that, in most cases, all of the Object Contexts are not closed.
For example, after running it locally, EF Profiler told me that there were 326 Object Context's opened, yet only 1 was closed?
So my question is, should I worry about this? Or is it self-contained within Entity Framework?
If you're not using an IoC container is there anyway you can close the ObjectContexts manually after each request, for example in the End Request of your Global.asax, thereby simulating a "per request" lifestyle for your contexts?
ObjectContexts will be disposed eventually if your application is not holding onto them explicitly, but in general, you should try to dispose them deterministically as soon as possible after you are done with them. In most cases, they will hold onto database connections until they are disposed. In my current web application, we use an IoC container (Autofac) to ensure that any ObjectContext opened during a request is disposed at the end of the request, and does not have to wait for garbage collection.
I suggest you do worry about it and try to fix the issue as Object Contexts are pretty "bulky". If you have too many of them your application may eventually end up using more memory than it needs to and IIS will be restarting your application more frequently then...
I have a few apps that I am trying to develop a reusable URL connection layer. I have done some research and am struggling between architectures. Specifically the APIs this layer utilizes.
In the past, I have used NSURLConnection and NSOperation on a separate RunLoop. This seems overkill. I've seen libraries that subclass NSURLConnection. Others have a singleton Engine object that manages all requests.
The Engine and/or NSURLConnection seem best to me. But I am asking for input before I go too far down one road. My goals would be:
Ability to cancel a request
Concurrent requests
Non-blocking
Data object of current open requests
Any direction or existing references with code samples would be greatly appreciated.
I'm not sure about a "data object of current open requests", but ASIHTTPRequest does the first three and is very easy to use.
Update
Actually, it looks like ASINetworkQueue may fulfill your last bullet point.
I personally use a singleton engine with my large Apps though it might not always be the best case. All the URL's I use require signing in first, figured it would be best if one Class handles all of the requests to prevent multiple URLS from signing into the one location.
I basically create a protocol for all my different connection classes into my singleton and pass the delegate of both the calling class and the singleton into it. If an error occurs its passed to the singleton so it can deal with it, if it completes it returns the data to the calling class.
Not even sure if the title is correct, however, what I'm trying to do is use the standard NSURLConnection class to handle responses from calling my webservice. I am using the POST method to update a database and the GET method to retrieve rows from the database. The problem I have is that these 2 actions may occur simultaneously so that the methods to handle the request may step on each other. In other words in my "connection didReceiveData" method I have 2 paths through the code depending on whether I'm handling a response from a GET or POST request.
I keep track on which request in being processed by an instance variable called requestType. The problem is that since the requests are being executed simultaneously the instance variable is being changed from GET to POST before the GET completes (or vice-versa). My question is how do I maintain 2 separate requests in this scenario? Do I synchronize the requests? Is there a way for threads to work here? Do I create 2 separate objects for each of the requests and have the logic in "didRecieveData" query for which object is being processed? Any help would be much appreciated!!
Dealt with a similar issue in one of our apps. The solution involved creating a class that represents a webservice call, responsible for calling its own url, loading its own data, etc. The call class had a delegate that would handle parsing the responses (in our case, a web service controller). Wound up getting rather complicated, but prevented the issue of NSURLConnections stepping on each other.
Seems like you've created a messy problem by having a class that tries to do too many things. I would suggest taking one of the following three approaches:
1) Write two classes, one for updates and one for retrievals. Each class creates it's own private NSURLConnection object and acts as the delegate for the async notifications received from the NSURLConnection. The classes could possible share some utility parsing code or extend a base object that has that parsing code in it. But the key being that the code calling these classes would instantiate one of them, make the call, and then release it. This will keep your code cleaner and will insure that the event notifications don't get intermingled.
2) Create a single class that, depending on initialization, does either a post or a get with it's own private instance of NSURLConnection. When a call needs to be made, instantiate the class, get the results, and then release the class.
3) Write your connection handling classes so they use the synchronous NSURLConnection method and call that call that class in a background thread.
Either way, clean code and clear object orientation will prevent messy scenarios like the one you're describing.
Create separate objects that handle the calls. If you want to issue multiple requests at once I would strongly recommend looking at NSOperationQueue, and making these objects subclasses of NSOperation... much nicer way to deal with multiple background requests.
A good example is here:
http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/
The idea there is that you use the non-asyncronous web calls, in operations that are run on separate threads. You can still use asynch calls in NSOperation as well, but doing so is a little trickier and for simple calls you probably do not need to.