After doing some research on MEF I came across the CreationPolicy.Shared property which according to MSDN:
Specifies that a single shared instance of the associated
ComposablePart will be created by the CompositionContainer and shared
by all requestors.
Sounds good as long as I always ensure that one and only one container ever accesses the class that I export with this policy. So how do I go about ensuring that only one container ever accesses my exported type? Here is my scenario:
I have a Windows service that needs to tap into a singleton-like class for some in-memory data. The data is non-persistent so I want it to be freshly created whenever the service starts up but it serves no purpose once the service is stopped. Multiple threads in my service will need to read and write to this object in a thread-safe fashion so my initial plan was to inherit from ConcurrentDictionary to ensure thread safe operations against it.
The threads that will be tapping into this class all inherit from a single abstract base class, so is there a way to have this class (and only this class) import it from MEF and have this work the way I want?
thanks for any tips you may have, I'm newish to MEF so I'm still learning the ins and outs
If it absolutely must be a singleton amongst different containers, you could use a private constructor and expose a static Instance property, as if it were a "classic" non-container-managed singleton. Then in the composition root, use ComposeExportedValue to register it with the container:
container.ComposeExportedValue(MySingleton.Instance);
You could always use the Lazy type since it blocks other threads as described in this blog post: http://geekswithblogs.net/BlackRabbitCoder/archive/2010/05/19/c-system.lazylttgt-and-the-singleton-design-pattern.aspx
Related
I have an existing C# ASP.NET application with a user interface and various buttons to initiate actions. The actions make synchronous method calls on a class which is a singleton and I'll call this class ServiceLayer. This layer also initializes a data model.
I want to schedule some of the actions from the UI to occur at certain times of day. I believe Quartz.NET provides all the necessary features I need to do this. I can successfully call methods on the singleton class ServiceLayer from the Execute(IJobExecutionContext context) of each Job class (i.e. classes which implement the IJob interface). However, I don't like using this approach for a few reasons:
Difficult to unit-test (e.g. I have to ensure the singleton is initialized before I can do anything)
Scaling up if many jobs are called
Thread safety issues associated with calling multiple methods on the singleton class at the same time.
My question is what is the best design pattern to handle this case instead of calling methods on a singleton directly? I believe I need to make use of the JobDataMap somehow but I'm not sure how. Should I be looking at a producer-consumer or a queuing approach?
You might want to consider implementing a custom job factory that injects your service layer object into the job. There are already implementations of custom factories for the most popular DI containers out there, so you could go with one of those or build your own. This would allow you to pass a reference to your service layer object each time you create a job and should help with unit testing. It would also resolve the singleton issue.
As far as scaling up is concerned, you could use the JobDataMap to pass in things like connection strings or server names, allowing you to load balance or distribute work across your servers.
Here are some posts describing the custom job factory approach if you end up going down that path.
Reading up on Lucene, it seems it's recommeneded to use the same instance of IndexSearcher across all requests.
If I have a search class which is injected using ninject
public interface IPatientSearch
{
void DoSearch(ref SearchDTO _search);
//...
}
Would there be any issues binding it using InSingletonScope, which would ensure the same instance is shared across all requests?
Bind<IPatientSearch>().To<PatientSearch>().InSingletonScope();
Am I missing any obvious pitfalls of using such an approach?
There's not an issue here from the Lucene.NET point of view; assuming your implementation of IPatientSearch creates an IndexWriter and uses that, there shouldn't be any problem. The IndexWriter class is thread-safe, and you won't have any troubles accessing your Lucene.NET index.
However, you have to make sure that all other aspects of the IPatientSearch implementation are thread-safe; if this singleton is accessed from multiple threads, then any other state that you have in the implementation has to be thread-safe. If your class is just a pass-through for calls to Lucene.NET, then you'll be fine, but if you have other state, then you need to make sure access to that state is synchronized.
You might want to create a thin abstraction around Lucene.NET and make that a singleton for the purposes of dependency injection, and have your other classes be instantiated normally (unless you need only one instance of that class).
The Static Vs. Singleton question has been discussed before many times in SO.
However, all the answers pointed out the many advantages of a singleton.
My question is - what are the advantages of a static class over a singleton?
Why not simply choose a singleton every time?
Static class is a technical tool in your box - basically a language feature.
Singleton is an architectural concept.
You may use a static class as a means to implement the singleton concept. Or you may use some other approach.
With static classes in C# there are two potential dangers if you're not careful.
The requested resources will not be freed until the end of application life
The values of static variables are shared within an application. Especially bad for ASP.NET applications, because these values will then be shared between all users of a site residing in a particular Application Domain.
From MSDN
Static classes and class members are used to create data and functions
that can be accessed without creating an instance of the class. Static
class members can be used to separate data and behavior that is
independent of any object identity: the data and functions do not
change regardless of what happens to the object. Static classes can be
used when there is no data or behavior in the class that depends on
object identity.
A key point is that static classes do not require an instance reference. Also note that static classes are specifically enabled by the language and compiler.
Singleton classes are just user coded classes implementing the Singleton design pattern. Singleton purpose is to restrict instantiation of an class to a single instance.
If you coded every static class as a singleton you'd have to instantiate the class every time you used it.
i.e.
Console.WriteLine('Hello World');
would become
Console c = Console.getInstance();
c.WriteLine('Hello World');
I'd say they're both (generally) poor solutions. There are a few use cases for static classes, primarily simple utility ones (Extension Methods in C# 3.0 come to mind). With any degree of complexity, though, testability issues start cropping up.
Say class A depends on static class B. You want to test class A in isolation. That's hard.
So you go with a Singleton. You have the same problem - class A depends on singleton B. You can't test class A in isolation.
When class B has other dependencies (such as hitting a database) or is mutable (other classes can change its global state), the problem is exacerbated.
IoC (Inversion of Control) container libraries are one solution to this problem; they let you define Plain Old Classes as having a long lifespan. When combined with a mocking library, they can make your code very testable.
Static classes are much easier to implement - I have seen many attempts at thread-safe singletons in C# that employs naive locking schemes instead of depending on the run-time's guaranteed one-time initialization of static fields (optionally inside a nested class to delay instantiation).
Other than that, I think singletons are great if you need to pass around a reference to an object that implements a specific interface, when that 'implemention' should be singleton, something which you cannot do with static classes.
One consideration I don't see mentioned is that preferring a solution using an instance of a class (singletons, or their DI equivalent) allows you to provide a class on which other users of your code may define extension methods -- since extension methods only work with non-static classes as the this parameter. In other words, if you have a line like:
GlobalSettings.SomeMethod();
Then syntactically the only thing that can be accessed via GlobalSettings are members you provide. In contrast, if GlobalSettings is an instance (singleton or otherwise) then consumers may add their own extensions to GlobalSettings that they would be unable to do otherwise:
application.GlobalSettings.CustomSomethingOrOther();
or
GlobalSettings.Instance.CustomSomethingOrOther();
The question leads to the need for a better understanding of what you are implementing, how it suppose to work, and what it should be capable of.
Let's say, you need some kind of Manager class that handles your object's in a particular way. Singleton requires a bit more work, but in return, it gives you the ability to treat your manager by its interface (IManager) rather than the strict name. With a static class, you obviously losing the inheritance, interfaces, and the ability to swap or reset the object by just re-instantiating it rather than manually zeroing all the static variables, but it also gets you rid of a bit of extra work in case if your static object is kept simple.
There are more extra details if you go deeper, but in general 99% of times, it's just a question of personal preference or your team's coding guidelines.
What would be the best way to implement a psuedo-session/local storage class in a console app? Basically, when the app starts I will take in some arguments that I want to make available to every class while the app is running. I was thinking I could just create a static class and init the values when the app starts, but is there a more elegant way?
I typically create a static class called 'ConfigurationCache' (or something of the sort) that can be used to provide application-wide configuration settings.
Keep in mind that you don't want to get too carried away with globals. I seriously recommend taking a look at your design and passing just what you need via method parameters. You're design should be such that each method receives a parameter for what is needed (see Code Complete 2 - Steve McConnell).
This isn't to say a static class is wrong but ask yourself why you need that over passing parameters into your various classes and methods.
If you want to take the command line arguments (or some other super-duper setting) and put them somewhere that your whole app can see, I don't know why you would consider it "inelegant" to put them in a static class when the app starts. That sounds exactly like what you want to do.
you could use the singleton design pattern if you need an object that you can pass around in your code but imo a static class is fine, too.
Frankly, I think the most elegant way would be to rethink your design to avoid "global" variables. Classes should be created or receive data they need to be constructed; methods should operate on those data. You violate encapsulation by making global variables that a class or classes need to do their jobs.
I would suggest possibly implementing a singleton class to manage your psuedo-session data. You'll have the ability to access the data globally while ensuring only one instance of the class exists and remains consistent while shared between your objects.
MSDN implementation of a singleton class
Think about your data as a configuration file required by all your classes. The file would be accessible from every class - so there is nothing really wrong with exposing the data through a static class.
But every class would have to know the path to the configuration file and a change of the path would affect many classes. (Of course, the path should better be a constant in only one class referenced by all classes riquiring the path.) So a better solution would be creating a class the encapsulates the access to the configuartion file. Now every class can create an instance of this class and access the configuartion data of the file. Because your data is not backed by a file, you would have to build something like a monostate.
Now you could start thinking about class coupling. Does it matter for you? Are you planning to write unit test and will you have to mock the configuration data? Yes? In this case you should start thinking about using dependency injection and accessing the data only through an interace.
So I suggest using dependency injection using an interface and I would implement the interface with the monostate pattern.
Closed as exact duplicate of this question. But reopened, as the other Singleton questions are for general use and not use for DB access
I was thinking of making an internal data access class a Singleton but couldn't convince myself on the choice mainly because the class has no state except for local variables in its methods.
What is the purpose of designing such classes to be Singletons after all?
Is it warranting sequential access to the database which is not convincing since most modern databases could handle concurrency well?
Is it the ability to use a single connection repeatedly which could be taken care of through connection pooling?
Or Is it saving memory by running a single instance?
Please enlighten me on this one.
I've found that the singleton pattern is appropriate for a class that:
Has no state
Is full of basic "Service Members"
Has to tightly control its resources.
An example of this would be a data access class.
You would have methods that take in parameters, and return say, a DataReader, but you don't manipulate the state of the reader in the singleton, You just get it, and return it.
At the same time, you can take logic that could be spread among your project (for data access) and integrate it into a single class that manages its resources (database connections) properly, regardless of who is calling it.
All that said, Singleton was invented prior to the .NET concept of fully static classes, so I am on the fence on if you should go one way or or the other. In fact, that is an excellent question to ask.
From "Design Patterns: Elements Of Reusable Object-Oriented Software":
It's important for some classes to
ahve exactly one instance. Although
there can be many printers in a
system, there should only be one
printer spooler. There should only be
one file system and one window
manager. ...
Use the Singleton pattern when:
there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point
the sole instance should be extensible by subclassing and clients should be able to use an extended instance without modifying their code
Generally speaking, in web development, the only things that should actually implement Singleton pattern are in the web framework itself; all the code you write in your app (generally speaking) should assume concurrency, and rely on something like a database or session state to implement global (cross-user) behaviors.
You probably wouldn't want to use a Singleton for the circumstances you describe. Having all connections to a DB go via a single instance of a DBD/DBI type class would seriously throttle your request throughput performance.
The Singleton is a useful Design Pattern for allowing only one instance of your class. The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.
Source: java.sun.com
using a singleton here doesn't really give you anything, but limits flexibility
you WANT concurrency or you won't scale
worrying about connections and memory here is a premature optimization
As one example, object factories are very often good candidates to be singletons.
If a class has no state, there's no point in making it a singleton; all well-behaved languages will only create, at most, a single pointer to the vector table (or equivalent structure) for dispatching the methods.
If there is instance state that can vary among instances of the class, then a singleton pattern won't work; you need more than one instance.
It follows, then, by exhaustion, that the only cases in which Singleton should be used is when there is state that must be shared among all accessors, and only state that must be shared among all accessors.
There are several things that can lead to something like a singleton:
the Factory pattern: you construct
and return an object, using some
shared state.
Resource pools: you have a shared
table of some limited resources,
like database connections, that you
must manage among a large group of
users. (The bumpo version is where
there is one DB connection held by
a singleton.)
Concurrency control of an external
resource; a semaphore is generally
going to be a variant of singleton,
because P/V operations must
atomically modify a shared counter.
The Singleton pattern has lost a lot of its shine in recent years, mostly due to the rise of unit testing.
Singletons can make unit testing very difficult- if you can only ever create one instance, how can you write tests that require "fresh" instances of the object under test? If one test modifies that singleton in some way, any further tests against that same object aren't really starting with a clean slate.
Singletons are also problematic because they're effectively global variables. We had a threading issue a few weeks back at my office due to a Singleton global that was being modified from various threads; the developer was blinded by the use of a sanctioned "Pattern", not realizing that what he was really creating was a global variable.
Another problem is that it can be pathologically difficult to create true singletons in certain situations. In Java for example, it's possible to create multiple instances of your "singleton" if you do not properly implement the readResolve() method for Serializable classes.
Rather than creating a Singleton, consider providing a static factory method that returns an instance; this at least gives you the ability to change your mind down the road without breaking your API.
Josh Bloch has a good discussion of this in Effective Java.
You have a repository layer that you want created once, and that reference used everywhere else.
If you go with a standard singleton, there is a bad side effect. You basically kill testability. All code is tightly couple to the singleton instance. Now you cannot test any code without hitting the database (which greatly complicates unit testing).
My advice:
Find an IOC that you like and integrate it into your application (StructureMap, Unity, Spring.Net, Castle Windsor, Autofac, Ninject...pick one).
Implement an interface for you repository.
Tell the IOC to treat the repository as a singleton, and to return it when code is asking for the repository by the interface.
Learn about dependency injection.
This is a lot of work for a simple question. But you will be better off.
with c#, I would say that a singleton is rarely appropriate. Most uses for a singleton are better resolved with a static class. Being mindful of thread safety is extremely important though with anything static. For database access, you probably don't want a single connection, as mentioned above. Your best bet is to create a connection, and use the built in pooling. You can create a static method that returns a fresh connection to reduce code, if you like. However an ORM pattern/framework may be better still.
In c# 3.5 extension methods may be more appropriate than a static class.