Caching ideas anyone? - c#

I have the following, very interesting class ...
pubilc class Thing{
public Thing()
{
DoSomethingThatTakesALongTime();
}
public boolean CheckSomething(string criteria)
{
return criteria == "something";
} }
In my ASP.Net MVC application, I need to make a call to CheckSomething very frequently.
As you can see, the constructor takes a long time to load.
What approaches can I use to cache the class? Keep in mind that I want to keep it testable ... and I don't know what that entails!!!!
Cheers,
ETFairfax

You could use the Factory Pattern to create it (Flyweight pattern to share memory)
Create a Factory that returns an instance of the class. The factory would look like this
if instance in cache
return cached instance
if not
create instance
cache instance
return instance
For cache you could use HttpContext Cache or Enterprise Library Cache.
EDIT
Interesting discussion below of which pattern this is.
My understanding is as follows:
I ask something to create the object, that something is a factory, therefore factory pattern.
I try to reuse an object in memory, flyweight pattern. The python code in this example looks very much like my answer: http://en.wikipedia.org/wiki/Flyweight_pattern
But there is only a single instance of the object, therefore the singleton pattern
The cache where the object is stored is also a singleton

You can create a static instance of that class.
Somewhere:
public static Thing singleThing = new Thing ();
Now upon the first access of the singleThing variable for a given application domain your constructor will work out. After this is done the object will be kept in memory until the end of the application domain (server restart, update of code, changes in web.config, recycling etc.). It means the once initialized object will be available to all clients of your application.

if your thing class does something global to your aplication (not session dependant) just make the class static or add the instance to the cache (HttpContext.Cache)

Related

How can I remove (set to null) a registered singleton type in DryIoC?

I have a requirement to completely delete an instance that is already resolved by DryIoC container (but not unregister the type). I don't know if this is possible?
If I don't use any IoC container and just declare singletons myself I of course can reset it to null easily whenever I want.
e.g:
var instance = DryIocContainer.Resolve<SomeType>();//a singleton
//All next times calling Resolve<> will return just that singleton instance.
//But if that is cleared, the next time calling Resolve<> should create
//a completely new instance (like as the first time it was called).
The scenario here is after user logging off my app, I want to clear all resolved singletons so that if the user logging back using another account (or even with that same account), the data will be refreshed correctly. Currently without being able to clear those singletons, I have to reset all properties manually myself - which I think should just be the last resort.
I don't know if this is possible?
No, this isn't really possible. Although Dadhi pointed to the WithoutSingletonsAndCache method, this effectively builds up a new container with a new set of instances. Although this allows you to replace your particular singleton, it also means that all other singleton registrations will be cleared and you lose the promise of there being only one instance of a particular type. In other words, in able to do this, the container has broken its promise around singletons. This effectively leads to a Torn Lifestyle. You will have closely analyse whether or not this will be a problem or not.
If I don't use any IoC container and just declare singletons myself I of course can reset it to null easily whenever I want.
This is not true. Even without a container, you can't simply replace a singleton. A simple example is when this singleton to be replaced is a dependency of another singleton. Unless you replace that singleton (and all its singleton consumers up the chain), this original instance is captured within its consumer and will the consumer will keep referencing the original instance, even though you try to replace it. This is a form of the Captive Dependency problem.
The only true way to solve this problem, and solve it locally for this instance only, is to create a Proxy for the abstraction of that Singleton. This proxy can wrap that dependency and you can allow it to be changed later on. This allows you to at any moment in time replace the dependency.
How to implement this, does highly depend on your particular needs, but here's an example:
public interface ISomeType
{
void SomeMethod();
}
public class SomeTypeImpl : ISomeType { ... }
public class SomeTypeProxy : ISomeType
{
public ISomeType Dependency { get; set; }
public SomeTypeProxy(ISomeType dependency) {
this.Dependency = dependency;
}
public void SomeMethod() => this.Dependency.SomeMethod();
}
Without a DI container, you can use this as follows:
var proxy = new SomeTypeProxy(new SomeTypeImpl());
// later on
proxy.Dependency = new OtherTypeImpl();
Another option is to let the Proxy wrap a Func<T> delegate, which allows you to move this logic to the delegate:
ISomeType dependency = new SomeTypeImpl();
var proxy = new SomeTypeProxy(() => dependency);
// later on
dependency = new OtherTypeImpl();
The scenario here is after user logging off my app, I want to clear all resolved singletons so that if the user logging back using another account
In your particular case, you are actually describing clearing the complete application. Your scenario sounds similar to restrarting the application. This is probably something that WithoutSingletonsAndCache works good at, because you wish to reset all singletons.
The same however can be achieved with just creating a new container with all its registrations. Your application will already have some sort of CreateContainer class, and it should be a matter of calling that CreateContainer method again.
Of course this method only works when your dealing with an application at only handles one user, instead of having a web application that runs requests for many users concurrently.
You can do:
container = container.WithoutSingletonsAndCache();
Here is the docs.

How to run test cases for Singleton object with multiple state?

I have a singleton object in C#.
This singleton object works based on some state assigned to it.
I dont have any method to switch state of singleton object at run time. Also I dont need it as application always start in one state and remains in same state.
Problem is while writing the test cases. I have written the test cases for each state. But I cant run it because the for all test cases I have single object with one state.
How to run the tests for other state. How to re-create the object for each test?
I dont want to change the singleton object code for test cases.
Any thought or idea will be much appreciated.
This is one of the reasons why it is handy not to manage the lifetime of a class yourself, but to have an Inversion of Control (IoC) container such as Autofac or Unity do it for you. You then simply create a class, that looks like any other class, and tell your IoC container to instantiate it as a singleton.
See also An Autofac Lifetime Primer.
In the case when you cannot use an IoC container (can't think of any, but let's be flexible), you can create an internal class that contains your "singleton"'s logic -- and this internal class is just that, an internal class, not a singleton...
internal class MyLogic
{
...
}
And then you wrap it in a public class, and make that a singleton. If you put both these classes together in a single Project, then the internal class (the implementation of your business logic) is not accessible to your application, only the public singleton version is accessible.
public sealed class MySingleton
{
private MySingleton() { Implementation = new MyLogic(); }
public static MySingleton Instance { ... }
private MyLogic Implementation { get; set; }
...
}
But then you can point out in your AssemblyInfo that your unit-test project does have access to the internal class by using
[assembly: InternalsVisibleTo("MySolution.UnitTests")]
This way, you can unit test your logic class while your application(s) can only use it as a Singleton.
Frankly I prefer the IoC way but if that's new to you, it's probably faster to implement the above solution instead.
Good luck!
I dont want to change the singleton object code for test cases.
Maybe it's the time to think about changing it for your whole program. Is there a reason you need this to be singleton? Singleton is a great pattern if you need it, but it's often misused by people who want to use global variables but have heard that they are evil. Now they program singletons, because they work the same while being one of those "patterns" that are cool OOP.
But a singleton is nothing but a global. And it has the same problems as a global. If you use that pattern, make sure you actually need it, because it comes with problems attached and you need to weight the benefits against the drawbacks. If you don't use the benefits, you only have drawbacks.
I would suggest you to avoid singletons when possible, see this talk by Misko Hevery: The Clean Code Talks

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...

SimpleServiceLocator: Why is automatic constructor injection not supported for singletons?

I've been experimenting with the SimpleServiceLocator, and I like it quite a bit, but there's one thing that I'm really frustrated by--you can't use automatic constructor injection for singletons. To make matters worse, you can't even use automatic constructor injection for its dependencies. You have to create the singleton object, all it's dependencies, all its dependencies dependencies, etc. manually.
Why is SimpleServiceLocator designed this way?
Aren't singletons supposed to be just like regular instances except that, upon the first request for an instance, that instance is stored and reused instead of a new one being created each time? Why does SimpleServiceLocator require an instance to be provided during the registration process rather than just allow the instance to be created and stored on first request?
I get that the point of SimpleServiceLocator is to not have a lot of bells and whistles and be really easy for beginners to use, but it seems like it's just designed incorrectly, and that the method for registering a singleton should be identical to the method for registering a regular instance except that the method name should be RegisterSingle<T>() instead of Register<T>(). Is there a reason for the more complicated (and seemingly less convenient) design I'm just not getting?
Meanwhile, is there another (preferably free) IOC container I can use that let's me register objects in code similarly to the SimpleServiceLocator but does allow automatic contructor injection for singletons (or at least allows automatic constructor injection for the dependencies of the singleton)?
The RegisterSingle<T> method is just a fancy helper method just to make life easier. What you can do with RegisterSingle<T> can also be done with the Register<T> method. The web site gives examples of this. You can register a single instance using the Register<T> method as follows (it uses a closure):
var weapon = new Katana();
container.Register<IWeapon>(() => weapon);
When you look at the lifestyle management examples on the web site, you can see the following example for creating a thread static instance:
[ThreadStatic]
private static IWeapon weapon;
container.Register<IWeapon>(
() => return weapon ?? (weapon = new Katana()));
I think this is the power of simplify, because there is almost nothing you can't do with this pattern. What you are trying to achieve is a bit harder, I must admit this, but nothing really advanced IMO. Here is the code you need to solve your problem:
private static IWeapon weapon;
container.Register<IWeapon>(
() => weapon ?? (weapon = container.GetInstance<Katana>()));
The trick is here to store the instance in a static variable (just as with the thread static), but now you should not create the instance yourself by newing it up, but you delegate the creation to the Simple Service Locator. This works, because –as you know- the SimpleServiceLocator will do automatic constructor injection when a concrete type is requested.
I must admit that it is a shame that we need to do this trickery. It would be nice if the library could actually do this for us. For instance, I can imagine a RegisterSingle<T> overload being added that allows us to do the following:
container.RegisterSingle<IWeapon>(
() => container.GetInstance<Katana>());
Please let me know what you think of such an overload. I'm always interested in feedback to make the library better. This would certainly be a nice feature for the next release.
Update:
Since release 0.14 we can do the following:
container.RegisterSingle<IWeapon, Katana>();
It won't get any easier than this.
Cheers
A typical singleton implementation has a private constructor, so the container cannot "see" it, call it, or detect dependencies.
Perhaps you are referring to the lifetime management features of some IoC containers, where you can configure the container to always return the same single instance of a class.
This is not what singleton means. Although the container returns the same instance, nothing prevents you from instantiating an instance in code using new.
A singleton, on the other hand, can only ever be instantiated once from any source (once per thread in some implementations). It does not expose a public constructor, rather a static method such as:
public class MySingleton
{
// note: not a thread-safe implementation
static MySingleton instance;
static DependencyThing thing;
private MySingleton(DependencyThing thing)
{
MySingleton.thing = thing;
}
public static MySingleton GetMySingleton(DependencyThing thing)
{
if(instance == null) instance = new MySingleton(thing);
return instance;
}
}
As you can see, you can't call new MySingleton() from outside the class itself. To "instantiate" the a MySingleton, you have to call MySingleton.GetMySingleton(thing). This call returns the sole instance or creates and then returns it.
SimpleServiceLocator has no way of knowing how to create this object, or from where to detect its dependencies.
This ability could be added if the API exposed something like
public void Register<T>(Expression<Func<T>> staticFactoryMethod)…
…in which case you could call Register(() => MySingleton.GetMySingleton());, but this would only work without parameters. There would have to be more overloads:
public void Register<T, TParam1>(Expression<Func<TParam1, T>> staticFactoryMethod)…
public void Register<T, TParam1, TParam2>(Expression<Func<TParam1, TParam2, T>> staticFactoryMethod)…
…so that the container would know what dependencies to instantiate and pass to the specified factory method.
All that said, it doesn't really make sense to have dependency injection with a singleton. Each subsequent call to GetMySingleton would have to ignore the arguments or alter the state of the singleton, which is almost certainly a very bad idea.

How to store class instance (helper class) in ASP.NET Cache?

I have a class instance which is created by using Activator.CreateInstance() method. That class instance contains helper methods which are frequently used throughout the application. In order to avoid creating the instance multiple times, I'm just thinking about implementing an appropriate caching mechanism.
The following consideration should be taken into account:
1) I can't use static class and methods.
2) There are around 6 instances (1 instance per class) per App Domain.
Your suggestion would be much appreciated!
If you want to avoid creating it multiple times, then don't use the ASP.Net cache object. The cache object specifically does not guarantee that anything you put in it will remain there. In fact it's one of the first things to be cannibalized if the server needs to free up resources.
A better option would be to use the HttpApplicationState object, which should be used to store objects that need to be globally accessible to all sessions. It also has built in thread safety if you access it properly.
The code to do it is as follows:
HttpContext.Current.Application.Lock();
HttpContext.Current.Application["myObject"] = myObject;
HttpContext.Current.Application.Unlock();
Utilizing it is just
var myObject = (MyObject)HttpContext.Current.Application["myObject"];
Use a singleton pattern:
class MySingleton {
private static MySingleton instance;
public MySingleton {
if(instance != null)
// One already created, the only call to this
// should come through Activator
throw...
instance = this;
}
public static MySingleton GetInstance() {
if(instance == null) instance = new MySingleton();
return instance;
}
}
The activator uses the public constructor. Then you can still retrieve the instance through GetInstance().
Ad 1) How about a static container for your instance? Along the lines of a singleton pattern?
Ad 2) 6 singletons or one static generic singleton class.
P.S.: I guess the static restriction is meant only for the helper class itself?
P.P.S.: Using HttpContext.Current.Application would be pretty much the same approach, except slower.
Sounds like a case for a dependency injection container. No matter which one you pick, they all have support for caching like a singleton, and it will do the Activator.CreateInstance part for you.
I like NInject for it's simplicity.

Categories