Using a Singleton pattern to Linq to Sql Data Context - c#

I have some confusion in Linq to SQL.I am searching for an actual reason why Data context class gives follwing Exception some times .
"There is already an open data reader associated with this command which must be closed first
Specially in multitasking environment.Most people are saying that the reason is ,Data Context is not thread Safe.All are suggesting to use DataContex as one per unit of work.
Please refer following thread for best answer
Linq-to-SQL Data Context across multiple threads
But in my case,i am using another class call "A" which is implemented in Singleton pattern.Purpose of this class is ,provide Data context object in singleton manner.I am maintaining instance of this class "A" as global instance in derived class and calling to Datacontex by using particular instance.
My question is,
Will my method call cause uncontrolled memory growth ? based on my understanding,singleton maintaining one instance as static object .If my assumption is wrong ,please give me good explanation.
Note:
Any way my method call also throws same exception.So i am sure same problem is happen in this scenario also.

Your approach will cause problems in general. A DataContext is not intended to be a singleton. Just don't do it.
Even if A is a singleton, create a new DataContext within the appropriate methods within A, rather than having a DataContext as a variable within A. (You might also want to consider whether A should really be a singleton in the first place.)

I actually came here because I felt a singleton pattern would be perfect for the Linq Datacontext too. But after seeing your issues it makes since why it's not.
Here's an example of how I'd write a Singleton Linq DataContext:
class DataAccess
{
private static DataContext db = null;
private DataAccess()
{
}
public static DataContext GetInstance()
{
return db ?? (db = new DataContext());
}
}
In the singleton pattern you set the DataContext instance as static. Well, in a multi-threaded environment a static object is going to cause collisions like the errors you're seeing. You are lucky to get those errors. Using multiple threads you could submit changes from another thread and then have the original thread submit causing a big mess.
I'd stick to non static implementation. True me I know it's disappointing, I really wanted to use that pattern here too.

Related

How to use a dbcontext in a static class? (ObjectDisposedException)

Hey I just recently learnt how to use extension methods and pretty excited to implement it in my current project.
My objective:
I want to check whether an entry exists in my table in a helper class, since I'm going to use it in multiple controllers to be able to determine which navigation links to show in my navbar:
My Issue:
I don't know how to access my dbcontext in my static helper class. My dbcontext controller takes an argument I don't know how to pass in my static class. I think creating a new dbcontext would solve my scope issue explained below but I don't see how I can pass the optional argument to my constructor.
It is currently configured in the Startup.cs class.
What I tried:
Passing the ApplicationDbContext as an argument. This works for a single method call in my controller, but when calling multiple extension methods (To check which game accounts the user has) I get a ObjectDisposedException.
ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'ApplicationDbContext'.
From what I understand it is a scope issue where the first method call disposes the context when it's done and I'm trying to use the same context in the next call? What can I do to work around that?
I tried reading this link Cannot access a disposed of object in ASP.NET Core when injecting DbContext but it didn't help me since it requires the ApplicationBuilder which is in the Startup.cs class.
Solution Update
I disposed the dbcontext after every method call because I put it into a variable. Instead, I call it directly on the passed context and it works:
Yeah, so, although the extensions are new and shiny to you, that doesn't mean you should use them for everything. First, extensions should have a logical connection to the type they're operating on. For example, if you have a string, something like ToUpper() makes sense as an extension because it modifies and returns a string. Something like what you're trying to do: just using the value of the reference to return a completely foreign type is a violation of the extension pattern.
Second, an extension should not interact with something like a database. In particular here, the static nature of an extension is completely incompatible with the concept of a EF context object. The only way you could even get it to work is to actually new up a context each time the extension is called, inside the extension. That's both a great way to screw up the EF object tracking stuff and a great way to leak memory.
Long and short, don't do this.
If you're just trying to factor out this code, you have better options. For example, you can actually just add methods directly to your context.
public class ApplicationDbContext : DbContext
{
...
public bool HasDota2Account(string id)
{
return Dota2Accounts.Any(m => m.ApplicationUserId == id);
}
}
Then, in your controller, you can simply do:
var hasDota2Account = context.HasDota2Account(User.Identity.GetUserId());
Never declare DbContext as static, it will cause all sorts of trouble, and not refresh the data, so you will be getting old data from a query. An option is to instantiate it inside the static method every time you use it, like this:
public static MyClass Example
{
public static bool MyStaticMethod(long id)
{
MyDBContext db = new MyDBContext();
//use db context now....
}
}

How to use Lazy<T> when extra context is required to create the object

Neither Lazy<T> nor Lazy<T, TMetadata> accept a Func<TSomething, T>. This seemingly makes it impossible to lazily create an object when the creation logic requires some extra context.
Here's a concocted example of what I'm trying to achieve:
private readonly Lazy<IDbConnection, IStatement> insertStatement =
new Lazy<IDbConnection, IStatement>(
conn => conn.CreateStatement(...));
public void Apply(IDbConnection connection)
{
this.insertStatement.GetValue(connection).Execute(...);
}
Here, an IDbConnection instance is required to create the IStatement housed by the Lazy instance. The assumption here is that once an IDbConnection is "known", it will remain the same. In other words, the IStatement does not need to change over time because the IDbConnection won't.
I've considered the alternative whereby my class takes an instance of IDbConnection in its constructor and creates the Lazy instances using a closure over that parameter. However, the reality is that obtaining the connection is an asynchronous operation and I'm having trouble seeing how I could make that happen before my dependent objects require it. This is a problem I intend pursuing, but still want to know the answer to this question...
Is there anything that facilitates scenarios whereby the factory used by Lazy can be passed some context that aids it in the creation of the object instance?
I can't comment, so, to try help you I need to post my comment like an answer.
If I understand correctly, you want to create a single Statement using a singleton Connection. If it's true what I'm thinking, maybe the code below can help you:
new Lazy<IStatement>(() => ConnectionSingleton.Instance.CreateStatement());
As you can see, you can delegate to other class the creation of the Statement

what is the advantage of Singleton Design Pattern

every one know how to write code for Singleton Design Pattern.say for example
public class Singleton
{
// Private static object can access only inside the Emp class.
private static Singleton instance;
// Private empty constructor to restrict end use to deny creating the object.
private Singleton()
{
}
// A public property to access outside of the class to create an object.
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
it is very clear that when we create a instance of any class many time the memory is allocated for each instance but in case of Singleton design pattern a single instance give the service for all calls.
1) i am bit confuse and really do nor realize that what are the reasons...that when one should go for Singleton Design Pattern. only for saving some memory or any other benefit out there.
2) suppose any single program can have many classes then which classes should follow the Singleton Design Pattern? what is the advantage of Singleton Design Pattern?
3 in real life apps when should one make any classes following Singleton Design Pattern?
thanks
Here is thread safe singleton
public sealed class MultiThreadSingleton
{
private static volatile MultiThreadSingleton instance;
private static object syncRoot = new Object();
private MultiThreadSingleton()
{
}
public static MultiThreadSingleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new MultiThreadSingleton();
}
}
}
return instance;
}
}
}
To assure only one and same instance of object every time.
Take a scenario, say for a Company application, there is only one CEO. If you want to create or access CEO object, you should return the same CEO object every time.
One more, after logging into an application, current user must return same object every time.
Other answers are good, as well. But they are providing examples of behavioural characteristics of the pattern. But, Singleton is more about creation. Thus one of the most important benefit of the pattern is that it is resource friendly. You are not wasting memory for a new object when you actually do not need a new one.
This causes another benefit, which is the instantiation overhead is avoided.
Benefits of Singleton Pattern:
• Instance control: Singleton prevents other objects from instantiating their own copies of the Singleton object, ensuring that all objects access the single instance.
• Flexibility: Since the class controls the instantiation process, the class has the flexibility to change the instantiation process.
The advantage of Singleton over global variables is that you are absolutely sure of the number of instances when you use Singleton, and, you can change your mind and manage any number of instances.
Real time usages/benefits of Singleton Design Pattern.
While using multi-threading, to manage the multi-thread Pool.
to manage the "service host repositories" in SOA (service oriented architecture).
for Logging Framework implementation
in automation Testing/Unit Testing project i.e. Coded UI projects.
While implementing the Caching in a big application.
for configuration settings to make proper control over the application.
One useful place to use a singleton is if it is accessing some resource that you only want to have a single access point for. For example, I've used it when writing some code to talk to a device. I only want one piece of code talking to the device so I use a singleton. Any attempt to create another instance of the object that talks to the device will just give you the same object back so I never have to worry about two instances maintaining out-of-sync data about the device or getting messages to and from the device mixed up or out-of-order.
But, of course, you are under no obligation to use them. They are just a tool that is sometimes useful.
Generally singleton is considered an anti-pattern in OOP because it means a class is asserting that with respect to the entire program - which in OOP it should have no knowledge of - it knows it's going to be the only one. That being said, singleton is the proper way to implement a constant in my experience. In general if something I was about to hard-code into a program (say a database username) then it can be moved to a Config file or a singleton.
One of few areas Java beats C# (in my opinion...) is its support for enums. Java offers truly OO constants via enums, and so this is how I will always implement a singleton in Java. C# has no ready-equivalent.
It can improve the way that memory is handled in the JVM and with memory being used properly, better performance will be reached. You are not creating multiple objects but trying to create only one, that way, there is less work for the Garbage collector and less memory occupation in the JVM heap.
for me i use singleton when i dont want to always getting data from my database if its not necessary. for example i created a singleton class for getting the data from my database once and only once, and use that data across my system, then i expose a method that will get the data(refresh) again when necessary or get the data when theres a new/modified data.
Let us assume there is one printer and all have to access that printer then while creating an object u should give access to only one person to print as it doesnt allow another person at the same time thats why in this situations in real life we need single ton classes where we can manage the tasks one by one with better clarity...

DAL Design/Load methods with NHibernate

public MyClass(int someUniqueID)
{
using(//Session logic)
{
var databaseVersionOfMyClass = session.CreateCriteria(/*criteria*/)
.UniqueResult<MyClass>();
//Load logic
}
}
The code sample above is my current direction, although I've reached a point where I need a bit of a sanity check.
With NHibernate(I'm green in this area), is it common or best practice to instantiate an object from a database within the class constructor? The alternative I believe, would be to have a static method that returns the object from the database.
I've also come across a relevent question regarding constructors vs factory methods, however I don't believe this implementation fits the factory methodology.
To add an additional question onto the above, if instantiation within the constructor is the way to go, I've always used some sort of Load() method in the past. Either a specific private method that literally matches properties from the returned db object to the new class, or via a generic reflective method that assumes property names will match up. I'm curious if there is another way to "load" an object that I've missed.
I do not like this approach.
IMHO , it is better to implement some kind of repository which retrieves instances of persisted classes for you.
As an alternative, you could also follow the ActiveRecord approach, where you could have a static 'Load' method inside your class, and an instance method 'Save' for instance. (Take a look at Castle ActiveRecord).
But, for me, I prefer the Repository approach.

Global Variable Access Solution Ideas

I have an initialization class that preloads content into a variable (probably a list or array). There will only be one instance of this initialization class but there will be many classes that need to access the preloaded content.
The problem is not many of them are related and none of them extend my initialization class. I thought about this for a bit and decided on using a static method and variable for this use. So something like this...
public class InitClass
{
static List PreloadedContent;
static ModelData GetContent(String ContentName)
{
//return the preloaded content that matches given name
}
}
The preloaded content may at some time decrease or increase in size depending on what the situation may call for. I've run into situations where something like this has been the only decent looking solution however; I think its an ugly solution.
Note: I can't load the data onto a class that needs it when it is created due to a variety of reasons - most of which are reasons I don't know about yet but will most likely come up. Certain classes will be loaded/unloaded depending on the rendering of the scene and my InitClass won't handle the creation of these objects most of the time.
Can anyone give me a better solution?
what you are doing is known as singleton. here are some previous discussions on this:
How to implement a singleton in C#
What’s a good threadsafe singleton generic template pattern in C#
To avoid static/global scope you could use some kind of Registry class. This means you have one class which you initialize at program startup. This class holds references to all other classes that need to be accessed globally.
Now you pass the initialized instance of your registry class to all instances in your application.
It isn't a very pretty soluation, but for me it is the best. With Static and global variables I always ended up in having some problems when testing or debugging code.
Another aproach would be to use a Singleton. Since they also just hold a static instance I would not prefer them.

Categories