how to dispose DomainContext? - wcf-ria-services

DomainContext consumes many memory when an instance created. If the instance is local variable, looks like the memory not released automatically with following code:
MyDomainContext ctx = new MyDomainContext();
....
ctx=null;
How to release a memory for the instance of a DomainContext?

DomainContext doesn't implements IDisposable so you must rely on GarbageCollector to free up your memory. Be sure to remove any reference to the DomainContext instance than call System.GC.Collect()
You shouldn't bother about the entities loaded by the domaincontext and still referenced somewhere in the code, as long as I know WCF Ria services keep only a WeakReference to them

Related

Scala: Making singleton to process a client request

Is it a good practice to make use of singleton object to process client requests?
As object instance is singleton, and if its in middle of processing a client request , and meanwhile another request arrives then same instance is invoked with new client data. Won't it make things messy?
When using singleton objects we must ensure everything inside it as well as everything it calls must be thread-safe. For example, javax.crypto.Cipher does not seem to be thread-safe, so it should probably not be called from a singleton. Consider how guice uses #Singleton to specify threadsafety intention:
#Singleton
public class InMemoryTransactionLog implements TransactionLog {
/* everything here should be threadsafe! */
}
Also consider the example of Play Framework which starting version 2.4 began moving away from singleton controllers and started encouraging class controllers.
It depends on whether the object holds any mutable data or not.
If the object is just a holder for pure functions and immutable state, it does not matter how many threads are using it at the same time because they can't affect each other via shared state.
If the object has mutable state then things can definitely go wrong if you access it from multiple threads without some kind of locking, either inside the object or externally.
So it is good practice as long as there is no mutable state. It is a good way of collecting related methods under the same namespace, or for creating a global function (by defining an apply method).

EF6 DbContext lifecycle issue

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

Using a static instance of DbProviderFactory in ADO.NET?

I am using the following code in my asp.net app. According to this code, for all users of the app, there will be only a single instance of DBProviderFactory. Will this create a problem in a multi-user environment? So all users would use the the same DbProviderFactory object to create connections. I am not sure if this will create some type of hidden problems in a multi-user environment.
The reason, why I am using a static instance for DbProviderFactory, is so that the GetFactory method is not called everytime a connection needs to be instantiated. This, I think, would make it quicker to get a connection object. Any flaw in my reasoning?
public class DatabaseAccess
{
private static readonly DbProviderFactory _dbProviderFactory =
DbProviderFactories.GetFactory(System.Configuration.ConfigurationManager.ConnectionStrings["DB"].ProviderName);
public static DbConnection GetDbConnection()
{
DbConnection con = _dbProviderFactory.CreateConnection();
con.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DB"].ConnectionString;
return con;
}
}
It looks fine, but probably will not create interesting efficiencies.
Object creation in .NET is quick. So creating the factory doesn't take a lot of time. Acquiring the connection from a remote database does, but with connection pooling, this normally isn't an issue.
The factory probably doesn't appear to implement any state of it's own & looks like it's probably immutable. So access from different threads is probably okay.
Static objects aren't garbage collected. I doubt the factory will grow in size, so this shouldn't be a problem.
So you avoid a bunch of cheap object creation, a bunch of cheap background garbage collections, and have a minor risk of a derived class actually having state and not being thread safe depending on the exact implementation returned by GetFactory

instance of class held by composition container in mef

I understand that a MEF CompositionContainer creates and keeps instances of classes. I don't know under what circumstances a CompositionContainer has a class instance in its bowels.
Can anybody list operations performed on the CompositionContainer or methods of the CompositionContainer class that cause the CompositionContainer to store an instance of a class within the CompositionContainer.
Is it possible to view class instances held within a CompositionContainer in the debugger or any other fashion?
The CompositionContainer will keep references to all shared parts for the lifetime of the CompositionContainer. (The default CreationPolicy is Any for both imports and exports, which means by default all parts will be shared unless otherwise specified.)
References to NonShared parts will be kept if the part implements IDisposable. The reference will be released when the root export that was pulled from the container is released (if that export was from a NonShared part). Exports can be released either by calling CompositionContainer.ReleaseExport, or ExportLifetimeContext.Dispose for exports created with an ExportFactory.
I don't think there's any simple way to view what's held by the CompositionContainer. The source code is available so you could theoretically dive into it and figure out exactly where it's stored.
In regards to your second question (#2 above) ...
Using the QuickWatch Window (Shift + F9) or a regular Watch window, copy the following in there:
((System.ComponentModel.Composition.Hosting.CompositionContainer)(this.Container))._catalogExportProvider._activatedParts
The line above assumes that the object you are stopped on has a "this.Container" property, which is the CompositionContainer of the scope you are referring to.
From there, you'll get an array of ActivatedParts. You then navigate the dictionary of Parts. Find the Part Definition you want to find the instance of, and expand its "Non-Public Members". There you will find the CachedInstance, and this will be the instance of your "Shared" exported part that's been created.
I think Parts that are exported NonShared and not IDisposable aren't cached or held onto at all. At least that's the behavior I've seen.

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.