What is the recommended way to instantiate another class inside a sealed class:
public sealed class AvayaService
{
private static Lazy<AvayaService> lazy =
new Lazy<AvayaService>(() => new AvayaService());
public static AvayaService AvayaServiceInstance
{
get
{
if (!lazy.IsValueCreated)
lazy = new Lazy<AvayaService>(() => new AvayaService());
return lazy.Value;
}
}
private AvayaService()
{
}
public static Response GetResponse(Request request)
{
var _repository = new Repository(); // what is the best way to get the instance here
}
}
public class Repository : IRepository
{
...
}
I am trying to learn sealed class and lazy instantiation however I am pondering over what should be the recommended way to instantiate another class in a sealed class?
There's no "recommendations" in this area. If you've read recommendations, read again, most probably it was just an exercise. It gives you an idea, but using this idea in a real project is up to you. Sometimes those exercises demonstrate an opposite approaches. Sometimes the repository owner will dictate the style which is against of any rules you've read before, and it's totally fine.
Here's another instantiation exercise which I think is helpful to try: to never instantiate anything except value objects. Delegate instantiation to a container. Avoid singleton pattern, but register your service as a singleton in your container. In this way your code will look like:
public sealed class AvayaService
{
private readonly IRepository _repository;
public AvayaService(IRepository repository)
{
if(repository == null)
throw new ArgumentNullException();
_repository = repository;
}
public static Response GetResponse(Request request)
{
// use _repository
}
}
Related
public sealed class HomePage : Page
{
public override void GoTo()
{
throw new System.NotImplementedException();
}
public override void IsAt() => Assert.IsTrue(Browsers.Title.Equals("home"));
}
I have bunch of page object classes like HomePage which I want to turn into a singleton.
I was looking at Jon Skeet's site on implementing the Singleton pattern.
An example of how to implement the Singleton pattern as per the site mentioned above:
public sealed class Singleton {
private static readonly Singleton instance = new Singleton();
static Singleton() {}
private Singleton() {}
public static Singleton Instance {
get {
return instance;
}
}
}
I want to implement this for all my page objects. All my page objects inherit from an abstract base class Page.
public abstract class Page
{
private static readonly Page instance = new Page();
public abstract void IsAt();
public abstract void GoTo();
}
I'm trying to implement the Singleton pattern I mentioned earlier on my Page base class. But the problem is my Page class is abstract and I can't do the following:
private static readonly Page instance = new Page(); // Since Page is abstract I can't do this.
How can I implement the singleton pattern without having to implement it for each child class individualy?
Your question is specifically about being able to implement the singleton pattern solely using the base class, without making any code changes to the derived classes.
It's possible to do something like this:
public abstract class Page
{
// Your normal Page base class things
}
public abstract class Page<T> : Page where T : Page<T>, new()
{
// Or whatever singleton pattern you want to implement
public static readonly T Instance = new T();
}
public class HomePage : Page<HomePage>
{
}
This lets you write:
var homePage = HomePage.Instance;
This works because Page<T> has its own set of static data which is separate for each T - so Page<HomePage> has separate static data to Page<LogInPage>.
You will however need to modify each of your pages to derive from Page<PageSubclass>, rather than from Page.
That said, I would take the simpler route of adding code like:
public static readonly HomePage Instance = new HomePage();
to each of your Page subclasses. This is significantly less "magic", doesn't rely on reflection to instantiate the pages, and will only take you a few minutes to add to even 70 page objects. After all, you'll have to modify them all to derive from Page<T> to use this pattern anyway.
You can kind of do this, but just because you can do something, it does not mean it is a good idea. Think if it really makes the code easier to understand or not. Sometimes the amount of abstraction makes it just not worth it
public abstract class Page<T> where T: new()
{
public static readonly T instance = new T();
public abstract void GoTo();
}
public class Home : Page<Home>
{
public override void GoTo()
{
Console.WriteLine("goto home");
}
}
public class Login : Page<Login>
{
public override void GoTo()
{
Console.WriteLine("goto Login");
}
}
Then:
Home.instance.GoTo();
Login.instance.GoTo();
The thing is it is not a nice pattern. You might be better doing something like this so you avoid singletons:
pages["Home"].Goto();
How do I go about creating a class which wraps all EF repository calls in a Using statement whilst also supporting an injectable interface of the repository?
I can't seem to wrap my head around having this class support 2 different types of instantiation.
public class MyClass(IRepo repo)
{
_repo = repo;
}
public void MyMethod()
{
using ( var db = new DbContxt() )
{
var repo = new Repo(db);
repo.GetById(1);
}
}
In essence, the life-time of the 'db' object is the lifetime of the method call. Whereas the lifetime of 'db' would be managed outside of the class if injected.
You could structure it this way:
public class MyClass
{
private readonly IRepo _repo;
//or if you want a parameterless constructor...
public MyClass() : this(new Repo()) { }
public MyClass(IRepo repo)
{
_repo = repo;
}
public MyObject MyMethod(int id)
{
_repo.GetById(id);
}
}
public interface IRepo
{
MyObject GetById(int id);
}
public class Repo : IRepo
{
public MyObject GetById(int id)
{
using ( var db = new DbContext())
{
//do your db related stuff here
}
}
}
You would need a way of injecting an instance of Repo into MyClass so maybe take a look at IoC.
This way, you can easily mock IRepo for testing purposes.
You shouldn't do it that way. Have a parameterless constructor for your Repo, and instantiate the DbContext there. You can also have an overload for it that takes a DbContext, but you don't have to go about it that way. The point is to let each layer only worry about what it needs on its own. Let the IOC container inject everything as it is created, don't make objects for a different layer inside your methods.
what is the 'best' way to manage the lifecycle of a disposable object when it is injected into another class. The example I keep running into is when running database queries using entity framework in a class that has a long lifetime.
Here is an example
public class CustomerViewModel
{
private ICustomerRepository _customerRepository;
public CustomerViewModel(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
public void AddCustomer(Customer customer)
{
_customerRepository.Customers.Add(customer);
_customerRepository.SaveChanges();
}
}
The code above looks perfectly innocent to me, however the _customerRepository object exists for as long as the CutomerViewModel exists for, which is much longer than it should.
If I were writting this code without DI i would do this:
public class CustomerViewModel
{
public void AddCustomer(Customer customer)
{
using (var customerRepository = new CustomerRepository())
{
customerRepository.Customers.Add(customer);
customerRepository.SaveChanges();
}
}
}
Which handles the lifecycle of CustomerRepository correctly.
How is this supposed to be managed when a class requires a Disposable object to have a shorter lifetime than itself?
The method I am using now is to create a RepositoryCreator object, which knows how to initialize a repository, but this feels wrong:
public class CustomerViewModel
{
private ICustomerRepositoryCreator _customerRepositoryCreator;
public CustomerViewModel(ICustomerRepositoryCreator customerRepositoryCreator)
{
_customerRepositoryCreator= customerRepositoryCreator;
}
public void AddCustomer(Customer customer)
{
using (var customerRepository = _customerRepositoryCreator.Create())
{
customerRepository.Customers.Add(customer);
customerRepository.SaveChanges();
}
}
}
UPDATE
So would doing something like this be preferable, it could be made generic but for the sake of this example I will not do this.
public class CustomerViewModel
{
private ICustomerRepository _customerRepository;
public CustomerViewModel(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
public void AddCustomer(Customer customer)
{
_customerRepository.Add(customer);
}
}
public class CustomerRepository : ICustomerRepository
{
private readonly DbContext _dbContext;
public CustomerRepository(DbContext dbContext)
{
_dbContext = dbContext;
}
public void Add(Customer customer)
{
_dbContext.Customers.Add(customer);
_dbContext.Customers.SaveChanges();
}
}
And have a proxy which manages lifetime
public class CustomerRepositoryLifetimeProxy : ICustomerRepository
{
private readonly _container;
public CustomerRepositoryLifetimeProxy(Container container)
{
_container = container;
}
public void Add(Customer customer)
{
using (Container.BeginScope()) //extension method
{
ICustomerRepository cRepo = Container.Resolve<ICustomerRepository>();
cRepo.Add(customer);
} // releases the instance
}
}
If this is better, should the Proxy know about the DI container, or should it rely on a factory?
The problem here is that your AddCustomer method in your ViewModel does to much. The viewmodel should not be responsible of handling business logic, and the repositories consumer shouldn't know nothing about committing a unit of work and should not be able to add a customer to the list of customers.
So instead, refactor your ICustomerResository to the following:
public interface ICustomerRepository
{
void Add(Customer customer);
}
In this case, the Add method should be atomic and do the commit itself. This way the viewmodel can depend on that interface and in case the viewmodel outlives the customer repository, you can wrap the real repository with a proxy:
public class CustomerRepositoryProxy : ICustomerRepository
{
private readonly Func<ICustomerRepository> repositoryFactory;
public CustomerRepositoryProxy(Func<ICustomerRepository> repositoryFactory) {
this.repositoryFactory = repositoryFactory;
}
public void Add(Customer customer) {
var repository = this.repositoryFactory.Invoke();
repository.Add(customer);
}
}
Of course this will start to become quite cumbersome if you have dozens of those IXXXRepository interfaces. In that case, you might want to migrate to one generic interface instead:
public interface IRepository<TEntity>
{
void Add(TEntity entity);
}
This way you can have one single proxy for all repositories:
public class RepositoryProxy<TEntity> : IRepository<TEntity>
{
private readonly Func<IRepository<TEntity>> repositoryFactory;
public CustomerRepositoryProxy(Func<IRepository<TEntity>> repositoryFactory) {
this.repositoryFactory = repositoryFactory;
}
public void Add(TEntity entity) {
var repository = this.repositoryFactory.Invoke();
repository.Add(entity);
}
}
In that case (assuming you wire your object graphs by hand) you can build up the viewmodel as follows:
new CustomerViewModel(
new RepositoryProxy<Customer>(
() => new CustomerRepository(unitOfWork)));
You can even take it one step further and implement the command/handler pattern and query/handler pattern. In that case you don't inject a IRepository<Customer> into your view model, but you inject an ICommandHandler<AddCustomer> into the view model and instead of injecting the AddCustomerCommandHandler implementation into the view model, you inject a proxy that creates the real handler when needed:
public class LifetimeScopedCommandHandlerProxy<TCommand> : ICommandHandler<TCommand>
{
private readonly Func<ICommandHandler<TCommand>> decorateeFactory;
public LifetimeScopedCommandHandlerProxy(
Func<ICommandHandler<TCommand>> decorateeFactory) {
this.decorateeFactory = decorateeFactory;
}
public void Handle(TCommand command) {
var decoratee = this.decorateeFactory.Invoke();
decoratee.Handle(command);
}
}
The view model will look as follows:
public class CustomerViewModel
{
private ICommandHandler<AddCustomer> addCustomerCommandHandler;
public CustomerViewModel(ICommandHandler<AddCustomer> addCustomerCommandHandler) {
this.addCustomerCommandHandler = addCustomerCommandHandler;
}
public void AddCustomer(Customer customer)
{
this.addCustomerCommandHandler.Handle(new AddCustomer(customer));
}
}
And the object graph will look similar as before:
new CustomerViewModel(
new LifetimeScopedCommandHandlerProxy<AddCustomer>(
() => new AddCustomerCommandHandler(unitOfWork)));
Of course, it will be much easier building these object graphs when using a container.
UPDATE
If you use a DI container, and you're not running in something like a web request, you will have to start a new 'scope' or 'request' explictly to inform the container what to do. With Simple Injector your proxy will looks like this:
public class LifetimeScopedCommandHandlerProxy<TCommand> : ICommandHandler<TCommand>
{
private readonly Container container;
private readonly Func<ICommandHandler<TCommand>> decorateeFactory;
// Here we inject the container as well.
public LifetimeScopedCommandHandlerProxy(Container container,
Func<ICommandHandler<TCommand>> decorateeFactory)
{
this.container = container;
this.decorateeFactory = decorateeFactory;
}
public void Handle(TCommand command) {
// Here we begin a new 'lifetime scope' before calling invoke.
using (container.BeginLifetimeScope())
{
var decoratee = this.decorateeFactory.Invoke();
decoratee.Handle(command);
}
// When the lifetime scope is disposed (which is what the using
// statement does) the container will make sure that any scope
// instances are disposed.
}
}
In that case your configuration might look like this:
// This instance lives as long as its scope and will be disposed by the container.
container.RegisterLifetimeScope<IUnitOfWork, DisposableUnitOfWork>();
// Register the command handler
container.Register<ICommandHandler<AddCustomer>, AddCustomerCommandHandler>();
// register the proxy that adds the scoping behavior
container.RegisterSingleDecorator(
typeof(ICommandHandler<>),
typeof(LifetimeScopedCommandHandlerProxy<>));
container.Register<CustomerViewModel>();
In general it is up to the creator to dispose a disposable object as soon es it is done with its usage. If your injected object can live through entire application lifecycle, i.e. without needing to dispose it in the meantime, than the normal DI approach (your first code block) is a good way to go. However, if you need to dispose the object as soon as possible, than a factory approach makes much more sense (last code block).
I am trying to make some generic factories for my service factories and dao factories and am running into some limitations.
Typically my service and dao factories look like this:
public static class PersonServiceFactory
{
private static PersonService personService;
public static PersonService GetInstance()
{
if (personService == null)
{
PersonDao personDao = PersonDaoFactory.GetInstance();
personService = new PersonService(personDao);
}
return personService;
}
}
public static class PersonDaoFactory
{
private static PersonDao personDao;
internal static PersonDao GetInstance()
{
if (personDao == null)
{
personDao = new PersonDao();
}
return personDao;
}
}
Then I tried doing a generic factories:
public abstract class EntityDaoFactory<daoClass>
where daoClass : class, new()
{
private static daoClass factorySupportClass;
internal static daoClass GetInstance()
{
if (factorySupportClass == null)
{
factorySupportClass = new daoClass();
}
return factorySupportClass;
}
}
public abstract class EntityServiceFactory<serviceClass, daoClass>
where serviceClass : class, new()
where daoClass : class
{
private static serviceClass factorySupportClass;
internal static serviceClass GetInstance()
{
if (factorySupportClass == null)
{
//daoClass daoSupportClass = *how to get daoSupportClassfactory.GetInstance(); here?*
factorySupportClass = new serviceClass(daoSupportClass);
}
return factorySupportClass;
}
}
So they could used like this:
public static class PersonDaoFactory : Entities.EntityDaoFactory<PersonDao>
{
}
public static class PersonServiceFactory : Entities.EntityServiceFactory<PersonService, PersonDaoFactory>
{
}
Here are the problems I am running into:
Can't use static class as type constraint for generics, which I was trying to use for the EntityServiceFactory, because without it I don't know how to inject the appropriate dao.
Can't have the factories derive from the Generic factories because I get an error like:
Static class 'Persons.PersonDaoFactory' cannot
derive from type
'Entities.EntityDaoFactory'.
Static classes must derive from object.
Tried making them all non-static classes with private constructors to get around that but then I get:
'Persons.PersonService' must be a non-abstract type with a public
parameterless constructor in order to use it as parameter
'serviceClass' in the generic type or method
'Entities.EntityServiceFactory
I was able to read why number 3 occurs on here, but that still doesn't solve my problems. I got the DaoFactory working, but it only works if the specific DaoClass doesn't need any dependency injection, otherwise error 3 pops up again.
Is there anyway to get these generic factories working using a different approach while still being able to use DI?
EDIT ----
I was able to get this sort of working, but it has some oddities. First I created a IEntityFactory interface:
public interface IEntityFactory<T>
where T : class
{
T GetInstance();
}
Then changed the EntityDaoFactory to:
public abstract class EntityDaoFactory<daoClass> : IEntityFactory<daoClass>
where daoClass : class, new()
{
private static daoClass factorySupportClass;
public daoClass GetInstance()
{
if (factorySupportClass == null)
{
factorySupportClass = new daoClass();
}
return factorySupportClass;
}
}
So I could pass in the appropriate type parameters and change the EntityServiceFactory to:
public abstract class EntityServiceFactory<serviceClass, daoClass, daoFactoryClass>
where serviceClass : class, new()
where daoClass : class, new()
where daoFactoryClass : IEntityFactory<daoClass>, new()
{
private static serviceClass factorySupportClass;
public static serviceClass GetInstance()
{
if (factorySupportClass == null)
{
daoFactoryClass daoSupportFactory = new daoFactoryClass();
daoClass daoSupportClass = daoSupportFactory.GetInstance();
factorySupportClass = new serviceClass();
}
return factorySupportClass;
}
}
So for a specific implementation such as with the Person object the calls look like:
public class PersonDaoFactory : Entities.EntityDaoFactory<PersonDao>
{
}
public class PersonServiceFactory : Entities.EntityServiceFactory<PersonService, PersonDao, PersonDaoFactory>
{
}
So it's working now, but the oddities are:
You can instantiate a factory, which was required (as far as I know the only way to do it?) for the EntityServiceFactory, but for someone using my API there would be no reason for them to do it but they still could.
Services and DAOs which have dependency requirements can now be instantiated with no parameters, which would break the instantiated class methods (but I had to do it to be able to use it as a type parameter). They shouldn't even ever by instantiating these objects anyway but they can now and do so incorrectly.
Also a final problem I just thought of is this solution doesn't really handle a variable amount of dependencies well. Still wonder if there is a better approach for this?
Conclusion: I think in the end even though it works, I gave up a lot of order to have that generic factory, which isn't that flexible and not giving me much, so I probably wouldn't use it in this case due to the limitations.
First of all, you are NOT using dependency injection. Depencency injection has nothing to do with providing type parameters to a generic class / method.
The errors occur because you are violating C#'s rules. You have to change your code to conform with them. So, make your classes non-static and do not use private constructors. You can replace a static class with a singleton instance and use protected constructors to avoid uncontroller instantiation.
I know that this question is really old, but I stumbled across it, so I figure I would give an answer.
The following compiles and does what you are looking to do:
public abstract class Entity<serviceFactory, serviceClass, daoFactory, daoClass>
where daoFactory : Entity<serviceFactory, serviceClass, daoFactory, daoClass>.DaoFactory, new()
where daoClass : class, new()
where serviceFactory : Entity<serviceFactory, serviceClass, daoFactory, daoClass>.ServiceFactory, new()
where serviceClass : class, new()
{
public abstract class DaoFactory
{
private static daoClass factorySupportClass;
internal static daoClass GetInstance()
{
if (factorySupportClass == null)
{
factorySupportClass = new daoFactory().createDao();
}
return factorySupportClass;
}
protected abstract daoClass createDao();
}
public abstract class ServiceFactory
{
private static serviceClass factorySupportClass;
internal static serviceClass GetInstance()
{
if (factorySupportClass == null)
{
daoClass daoSupportClass = DaoFactory.GetInstance();
factorySupportClass = new serviceFactory().createService(daoSupportClass);
}
return factorySupportClass;
}
protected abstract serviceClass createService(daoClass dao);
}
}
Now unless you are planning on using these types from within a composition root, I strongly recommend against doing the above solution since some of your dependencies are hidden and worse, are fixed to a limited set of parameters. Instead try something like this for a more DI/composition root friendly solution.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I need to store a bunch of variables that need to be accessed globally and I'm wondering if a singleton pattern would be applicable. From the examples I've seen, a singleton pattern is just a static class that can't be inherited. But the examples I've seen are overly complex for my needs. What would be the very simplest singleton class? Couldn't I just make a static, sealed class with some variables inside?
Typically a singleton isn't a static class - a singleton will give you a single instance of a class.
I don't know what examples you've seen, but usually the singleton pattern can be really simple in C#:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
static Singleton() {} // Make sure it's truly lazy
private Singleton() {} // Prevent instantiation outside
public static Singleton Instance { get { return instance; } }
}
That's not difficult.
The advantage of a singleton over static members is that the class can implement interfaces etc. Sometimes that's useful - but other times, static members would indeed do just as well. Additionally, it's usually easier to move from a singleton to a non-singleton later, e.g. passing in the singleton as a "configuration" object to dependency classes, rather than those dependency classes making direct static calls.
Personally I'd try to avoid using singletons where possible - they make testing harder, apart from anything else. They can occasionally be useful though.
There are several Patterns which might be appropriate for you, a singleton is one of the worse.
Registry
struct Data {
public String ProgramName;
public String Parameters;
}
class FooRegistry {
private static Dictionary<String, Data> registry = new Dictionary<String, Data>();
public static void Register(String key, Data data) {
FooRegistry.registry[key] = data;
}
public static void Get(String key) {
// Omitted: Check if key exists
return FooRegistry.registry[key];
}
}
Advantages
Easy to switch to a Mock Object for automated testing
You can still store multiple instances but if necessary you have only one instance.
Disadvantages
Slightly slower than a Singleton or a global Variable
Static Class
class GlobalStuff {
public static String ProgramName {get;set;}
public static String Parameters {get;set;}
private GlobalStuff() {}
}
Advantages
Simple
Fast
Disadvantages
Hard to switch dynamically to i.e. a Mock Object
Hard to switch to another object type if requirements change
Simple Singleton
class DataSingleton {
private static DataSingleton instance = null;
private DataSingleton() {}
public static DataSingleton Instance {
get {
if (DataSingleton.instance == null) DataSingleton.instance = new DataSingleton();
return DataSingleton;
}
}
}
Advantages
None really
Disadvantages
Hard to create a threadsafe singleton, the above Version will fail if multiple threads access the instance.
Hard to switch for a mock object
Personally I like the Registry Pattern but YMMV.
You should take a look at Dependency Injection as it's usually considered the best practice but it's too big a topic to explain here:
Dependency Injection
A Singleton isn't just a static class that can't be inherited. It's a regular class that can be instantiated only once, with everybody sharing that single instance (and making it thread safe is even more work).
The typical .NET code for a Singleton looks something like the following. This is a quick example, and not by any means the best implementation or thread-safe code:
public sealed class Singleton
{
Singleton _instance = null;
public Singleton Instance
{
get
{
if(_instance == null)
_instance = new Singleton();
return _instance;
}
}
// Default private constructor so only we can instanctiate
private Singleton() { }
// Default private static constructor
private static Singleton() { }
}
If you're going to go down the path you're thinking, a static sealed class will work just fine.
Using C# 6 Auto-Property Initializers.
public sealed class Singleton
{
private Singleton() { }
public static Singleton Instance { get; } = new Singleton();
}
Short and clean - I'll be happy to hear the downsides.
I know this Issue is old, but here is another solution using .Net 4.0 or later (including .Net Core and .Net Standard).
First, define your class that will be transformed into a Singleton:
public class ClassThatWillBeASingleton
{
private ClassThatWillBeASingleton()
{
Thread.Sleep(20);
guid = Guid.NewGuid();
Thread.Sleep(20);
}
public Guid guid { get; set; }
}
In this Example Class I've defined one constructor that Sleeps for a while, and then creates one new Guid and save to it's public property. (The Sleep is just for concurrency testing)
Notice that the constructor is private, so that no one can create a new instance of this class.
Now, We need to define the wrapper that will transform this class into a singleton:
public abstract class SingletonBase<T> where T : class
{
private static readonly Lazy<T> _Lazy = new Lazy<T>(() =>
{
// Get non-public constructors for T.
var ctors = typeof(T).GetConstructors(System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic);
if (!Array.Exists(ctors, (ci) => ci.GetParameters().Length == 0))
throw new InvalidOperationException("Non-public ctor() was not found.");
var ctor = Array.Find(ctors, (ci) => ci.GetParameters().Length == 0);
// Invoke constructor and return resulting object.
return ctor.Invoke(new object[] { }) as T;
}, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);
public static T Instance
{
get { return _Lazy.Value; }
}
}
Notice that it uses Lazy to create a field _Lazy that knows how to instantiate a class using it's private constructor.
And it defines one Property Instance to access the Value of the Lazy field.
Notice the LazyThreadSafetyMode enum that is passed to the Lazy constructor. It is using ExecutionAndPublication. So only one thread will be allowed to initialize the Value of the Lazy field.
Now, all we have to do is define the wrapped class that will be a singleton:
public class ExampleSingleton : SingletonBase<ClassThatWillBeASingleton>
{
private ExampleSingleton () { }
}
Here is one example of the usage:
ExampleSingleton.Instance.guid;
And one test to assert that two threads will get the same instance of the Singleton:
[Fact()]
public void Instance_ParallelGuid_ExpectedReturnSameGuid()
{
Guid firstGuid = Guid.Empty;
Guid secondGuid = Guid.NewGuid();
Parallel.Invoke(() =>
{
firstGuid = Singleton4Tests.Instance.guid;
}, () =>
{
secondGuid = Singleton4Tests.Instance.guid;
});
Assert.Equal(firstGuid, secondGuid);
}
This test is calling the Value of the Lazy field concurrently, and we want to assert that both instances that will be returned from this property (Value of Lazy) are the same.
More details about this subject can be found at: C# in Depth
So, as far as I am concerned, this is the most concise and simple implementation of the Singleton pattern in C#.
http://blueonionsoftware.com/blog.aspx?p=c6e72c38-2839-4696-990a-3fbf9b2b0ba4
I would, however, suggest that singletons are really ugly patterns... I consider them to be an anti-pattern.
http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx
For me, I prefer to have something like a Repository, implementing IRepository. Your class can declare the dependency to IRepository in the constructor and it can be passed in using Dependency Injection or one of these methods:
http://houseofbilz.com/archive/2009/05/02.aspx
Use your language features.
Mostly simple thread-safe implementation is:
public sealed class Singleton
{
private static readonly Singleton _instance;
private Singleton() { }
static Singleton()
{
_instance = new Singleton();
}
public static Singleton Instance
{
get { return _instance; }
}
}
...what would be the very simplest singleton class?
Just to add one more possible solution. The simplest, most straight forward and easy to use approach I can think of would be something like this:
//The abstract singleton
public abstract class Singleton<T> where T : class
{
private static readonly Lazy<T> instance = new Lazy<T>( CreateInstance, true );
public static T Instance => instance.Value;
private static T CreateInstance()
{
return (T)Activator.CreateInstance( typeof(T), true);
}
}
//This is the usage for any class, that should be a singleton
public class MyClass : Singleton<MyClass>
{
private MyClass()
{
//Code...
}
//Code...
}
//Example usage of the Singleton
class Program
{
static void Main(string[] args)
{
MyClass clazz = MyClass.Instance;
}
}