Singleton Inheritance C# - c#

I was trying to implement a singleton inheritance for my log system, so I would be able to separate the system events from user behavior. I found this nice post in Java. Despite the Generics difference I could implemente this attached first version (non thread safe for a while).
public abstract class Log
{
private static volatile Dictionary<Type, Log> instances = new Dictionary<Type, Log>();
public static Log GetInstance(Type type) {
Log instance = null;
if (!Log.instances.ContainsKey(type))
{
ConstructorInfo ctor = type.GetConstructor(BindingFlags.Default,
null,
new Type[0],
new ParameterModifier[0]);
instance = ctor.Invoke(new object[0]) as Log;
instances.Add(type, instance);
}
else
{
instance = Log.instances[type];
}
return instance;
}
private Log() { }
public class UserLog : Log
{
private UserLog() : base() { }
}
public class SystemLog : Log
{
private SystemLog() : base() { }
}
}
The highlight line above shows the attempt to create a new instance. But is doesn't work and returns a null instance of ConstructorInfo.
1) Any ideia about how to use the GetConstructor method? I know it has 3 overloaded versions, but the first one is only for public constructors. If I change the visibility of the constructor to public I can use other overloaded version (this one), but this specific version I can't even with public constructors.
2) In C#, is it possible to call a private constructor from other class like I'm trying to do? I have implemented it in Java, but in C# it might be different.

Since your binding flags don't specify Private, you won't get your private constructors. If there were public, you'd need to specify Public.
That said, I don't understand your desire to implement this in this way. It seems like a lot of extra work for no good reason.
I would do it like this:
public abstract class Log
{
public class UserLog : Log
{
private static readonly Lazy<UserLog> _instance =
new Lazy<UserLog>(() => new UserLog());
public static UserLog Instance { get { return _instance.Value; } }
}
public class SystemLog : Log
{
private static readonly Lazy<SystemLog > _instance =
new Lazy<SystemLog >(() => new SystemLog ());
public static SystemLog Instance { get { return _instance.Value; } }
}
}
I.e. just follow the normal singleton idiom for each of the actual singleton classes.

If you specify that the generic type will have to inherit from Log, and that it will have the new(), you can get away with using the parameterless constructor. You also would have to change your constructor to protected so that the child class can call it:
public abstract class Log
{
private static volatile Dictionary<Type, Log> instances = new Dictionary<Type, Log>();
public static TLogType GetInstance<TLogType>() where TLogType : Log, new()
{
TLogType instance = null;
var type = typeof(TLogType);
if (!Log.instances.ContainsKey(type))
{
instance = new TLogType();
instances.Add(type, instance);
}
else
{
instance = (TLogType)Log.instances[type];
}
return instance;
}
protected Log() { }
}
I don't think you can call the private constructors outside the class (they are private, after all), but through reflection there may be something that can be done (I'm no reflection expert). Using protected instead of private may get you the results you want.

Related

How to access classes with on one instance?

I have multiple classes in the service layer of my app.
Let's say I need to access some method from AbcService.cs in my controller. Then, I need to access some method from XyzService.cs in the same controller. Then another.......For this, I would need to create an object of each Service class separately in the constructor. Also, if I needed to access these methods in another cntroller I would again have to create objects of AbcService, XyzService, etc. I want to have one instance that can give me access to methods of all service classes.
Something like:
generalService.AbcService.MethodName();
generalService.AbcService.MethodName();
How do I do this in the best possible way?
You can use inheritance and create a class that (eventually) inherits from all of them, thus inheriting their methods. Or you can make them inherit from each other (this way you'll have to use the service class that inherits from both, as it would have all the methods that can be inherited).
To put it very simply, it can go like this using inheritance (I assume the service classes were not inheriting from anything until now):
public class ServiceClassA
{
//Certain Methods
}
public class ServiceClassB : ServiceClassA
{
//Other methods, this class also has ServiceClassA methods
}
public class ServiceClassC : ServiceClassB
{
//Even more methods, this class also has ServiceClassA and ServiceClassB methods
}
//... and so on
Assuming the lowest class in the inheritance tree is ServiceClassC for example, you only need a ServiceClassC object and you'll be able to access the needed (inherited) methods.
Create service layer so that other componentns can access easily.
public class Program
{
static void Main(string[] args)
{
Global.ServiceABC.MethodA();
Global.ServiceXYZ.MethodB();
}
}
public class Global
{
private static ABC serviceABC;
public static ABC ServiceABC { get
{
if (serviceABC == null)
{
serviceABC = new ABC();
}
return serviceABC;
}
}
private static XYZ serviceXYZ;
public static XYZ ServiceXYZ
{
get
{
if (serviceXYZ == null)
{
serviceXYZ = new XYZ();
}
return serviceXYZ;
}
}
}
public class ABC
{
public void MethodA() { }
}
public class XYZ
{
public void MethodB() { }
}
Unfortunately in C# you can NOT inherit from two classes at once so something like
public class CombinedService : AbcService, XyzService {
}
is not possible.
You can however use static methods to have only one instance per service like this:
public static class ServiceManager {
// The variable holding the instance
private static AbcService _abcService = null;
// Access to the instance and single instance creator
public static AbcService AbcServiceInstance {
get {
if (_abcService == null) {
// Create your Instance here
_abcService = new AbcService();
}
return _abcService;
}
}
// The variable holding the instance
private static XyzService _xyzService = null;
// Access to the instance and single instance creator
public static XyzService XyzServiceInstance {
get {
if (_xyzService == null) {
// Create your Instance here
_xyzService = new XyzService();
}
return _xyzService;
}
}
}
Because they are static you can access them from everywhere in the code just by calling the static class properties like this:
ServiceManager.AbcServiceInstance.SomeMethod();
ServiceManager.XyzServiceInstance.SomeMethod();
You can also shorten the instantiation and accessor like this:
private static AbcService _abcService = new AbcService();
public static XyzService XyzServiceInstance {
get { return _abcService; }
}
If the instances can just be created like this and don't need any more parameters or configuration.
You should consider using a dependency injection container like Autofac. Register your service classes as Single Instance scope. You will get only one instance of a service class whenever you request it in every individual controller and even you do not need to create instance of it on your own.All is done by Ioc Container.
var builder = new ContainerBuilder();
builder.RegisterType<SomeService>().SingleInstance();
It somewhat depends how you choose to implement your services, but generally speaking you want some layer that encapsulate your services which is a singleton or that you inject\produce a single instance of it.
Encapsulation:
First try to look at a facade design pattern.
http://www.dofactory.com/net/facade-design-pattern
And btw if you don't need something complex and don't mind have an extra level of indirection then you can have some version of the facade like
KindOfSimpleFacade
{
public IServiceA ServiceA { get; }
public IServiceB ServiceB { get; }
}
Regarding the singleton there are a few ways to get it:
inject the facade object to the (just provide the same instance to each one of the controllers as an input).
(Facade) Factory -http://tutorialspoint.com/design_pattern/factory_pattern.htm
The factory will produce a single instance of the facade.
use static members inside the facade for example:
public class KindOfSimpleFacade
{
private static readonly serviceA = new ServiceA();
private static readonly serviceB = new ServiceB();
public IServiceA ServiceA { get { return serviceA; } }
public IServiceB ServiceB { get { return serviceB; } }
}

Correct Usage of the Singleton Pattern

I have a requirement where only one instance of BillLines is ever created, which is of course perfect for the singleton pattern.
Looking at Jon's Skeet's post I'm not quite understanding where I create my 'new' object (i.e. the useful object not some abstract Singleton object).
Does this appear correct to you?
public sealed class ContextSingleton
{
private static readonly Lazy<ContextSingleton> Lazy =
new Lazy<ContextSingleton>(() => new ContextSingleton());
public static ContextSingleton Instance { get { return Lazy.Value; } }
private ContextSingleton()
{
}
//Is this correct? Where should I 'new' this?
public readonly IBillLineEntities Context = new BillLines.BillLines();
}
Being accessed like this:
var contextSingleton = ContextSingleton.Instance.Context;
Update
I don't have access to the internals of BillLines but I need to ensure only one instance of it exists.
I assume BillLines should be your Instance variable.
It should look like this:
public static class ContextSingleton
{
private static readonly Lazy<BillLines> _instance =
new Lazy<BillLines>(() => new BillLines());
public static BillLines Instance { get { return _instance.Value; } }
private ContextSingleton()
{
}
}
And you use it like this:
ContextSingleton.Instance
Edit
This answer was targeting the creation of a singleton about a specific class. If other people have access to your BillLines class and can create their own instance of it, then you should probably rethink what you're trying to do. If you do control the exposure of your BillLines class, you should make it so it is only exposed in the internal implementation of the singleton you're exposing, so no other person can create a new BillLines as they see fit.
Something simple like this?
public class BillLines
{
private BillLines()
{
}
private static BillLines _billLines = null;
public static BillLines Instance
{
get
{
if (_billLines == null)
_billLines = new BillLines();
return _billLines;
}
}
}
Thanks to the comments from #JonSkeet and #RobH I went down the dependency injection route. I picked Ninject and this does the job as I expected:
public class NinjectBindings : NinjectModule
{
public override void Load()
{
Bind<IBillLineEntities>.To<BillLines.BillLines>().InSingletonScope();
}
}

C# singleton definition

I saw implementation like that:
class MyClass
{
private static readonly MyClass _instance = new MyClass();
public static MyClass Instance{
get{ return _instance; }
}
}
Why not make it simple?
class MyClass
{
public static readonly MyClass Instance = new MyClass();
}
You can expose public fields like this - but I prefer not to. If you leave it as a property, you can change the implementation later. For example, suppose you later add a static method which you want to be able to call without initializing the singleton - with the property version, you could change the code to:
public sealed class MyClass
{
public static MyClass Instance { get { return InstanceHolder.instance; } }
private MyClass() {}
private static class InstanceHolder
{
internal static readonly MyClass instance = new MyClass();
}
public static void Foo()
{
// Calling this won't initialize the singleton
}
}
(With the original version, the singleton might be initialized, or it might not be - it's up to the CLR.)
That's just one example of why you might want to change the implementation later. With a property, you can do that - with a field, you can't.
What you've got there would work fine, but public fields are usually frowned upon in favour of Properties. You can change the implementation of the get { ... } without needing to change calling code. This would enable you to (for example) switch to lazy initialisation where the Instance is only created the first time it is used.
Note that although the calling code wouldn't need to change, it would change the signature of your class since a readonly property is different to a readonly field.

How to create a fully lazy singleton for generics

I have the following code implementation of my generic singleton provider:
public sealed class Singleton<T> where T : class, new()
{
Singleton()
{
}
public static T Instance
{
get { return SingletonCreator.instance; }
}
class SingletonCreator
{
static SingletonCreator()
{
}
internal static readonly T instance = new T();
}
}
This sample was taken from 2 articles and I merged the code to get me what I wanted:
http://www.yoda.arachsys.com/csharp/singleton.html and
http://www.codeproject.com/Articles/11111/Generic-Singleton-Provider.
This is how I tried to use the code above:
public class MyClass
{
public static IMyInterface Initialize()
{
if (Singleton<IMyInterface>.Instance == null // Error 1
{
Singleton<IMyInterface>.Instance = CreateEngineInstance(); // Error 2
Singleton<IMyInterface>.Instance.Initialize();
}
return Singleton<IMyInterface>.Instance;
}
}
And the interface:
public interface IMyInterface
{
}
The error at Error 1 is:
'MyProject.IMyInterace' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'MyProject.Singleton<T>'
The error at Error 2 is:
Property or indexer 'MyProject.Singleton<MyProject.IMyInterface>.Instance' cannot be assigned to -- it is read only
How can I fix this so that it is in line with the 2 articles mentioned above? Any other ideas or suggestions are appreciated.
Does my implementation break the Singleton pattern?
Basically, you've given a class constraint on your singleton class, along with the new() constraint.
When writing
Singleton<IMyInterface>
you're using an interface type as T, which violates the type constraint you defined.
For error 2,
Singleton<IMyInterface>.Instance = CreateEngineInstance();
you're trying to assign a value to a read-only property. So you need to define a setter on your Instance property for that line to work.
Update
Something along these lines should do it for you :
public sealed class Singleton
{
private static Hashtable bindings = new Hashtable();
private static Hashtable instances = new Hashtable();
private static void checkType(Type requested, Type bound)
{
if (requested.IsValueType)
throw new Exception("Cannot bind a value type to a reference type");
// also check type inheritance and other things...
}
private static void checkBinding(Type requested)
{
if (!(bindings.ContainsKey(requested)))
throw new Exception(String.Format("Type {0} was not bound !", requested.FullName));
}
public static void Bind<T, U>() where U : class, new()
{
checkType(typeof(T), typeof(U));
bindings[typeof(T)] = typeof(U);
}
public static T GetInstance<T>()
{
Type requested = typeof(T);
Type bound = (Type) bindings[requested];
checkBinding(requested);
if (!instances.ContainsKey(requested)) {
// We know that type "bound" was set with a new() class constraint
instances[requested] = (T) Activator.CreateInstance(bound);
}
return (T) instances[requested];
}
}
You could then write :
Singleton.Bind<IMyInterface, MyClass>();
IMyInterface instance = Singleton.GetInstance<IMyInterface>();
If you want to go further, you could also specify the lifecycle of the objects created by this provider, so that you could use singletons, or have the provider return a new object for each call, and so on.
You should also take a look at the Dependency Injection pattern, which seems close to what you want achieve, and also look at existing DI frameworks (NInject, Nhibernate) that already do this and much more.
Sure, you have an issue there. You generic is suppose to take class, not interface.
internal static readonly T instance = new T();
Your code suppose to create an instance of that class, you could not instantiate interface type.
So, if you need some type to act as singletone, you should write:
Singleton<MyInterface>.Instance
where
public class MyInterface : IMyInterface { }
Then you don't need to have any 'if' in you code, since it Singleton responsibility to instantite an object and keep it as only one instance.
Not related to question: currently Singletone's are considered by many developers as 'code-smell', so in general you have to avoid them. Try to think you application without Singletone at all.

Static Class as an Instance Property

I have an interface based class that I want to have a few static classes as properties. However, I can't seem to find a way to use a static class as an instance property on a class based on an interface.
public interface IHttpHelp
{
ItemsManager {get;set;}
}
public static class ItemsManager
{
//static methods
}
public class HttpHelper
{
public ItemsManager { get { return ItemsManager;}
}
The above code won't work because of the "ItemsManager is used like a variable but it's a type error." Is there anyway to use a class this way?
For some insight into what I'm doing - I have a few static helper classes that access the httpruntime and current context. I currently use them directly, but wanted to move into a container class that will be used IoC. I could make them instance classes and forget about it, but I'm wondering f there's a way to this.
You can't use a static class like that, because by definition you can't create an instance of it, so you can't return it from a property. Make it a singleton instead:
public class ItemsManager
{
#region Singleton implementation
// Make constructor private to avoid instantiation from the outside
private ItemsManager()
{
}
// Create unique instance
private static readonly ItemsManager _instance = new ItemsManager();
// Expose unique instance
public static ItemsManager Instance
{
get { return _instance; }
}
#endregion
// instance methods
// ...
}
public class HttpHelper
{
public ItemsManager ItemsManager { get { return ItemsManager.Instance; } }
}
This is not supported by the language directly. You can either write a proxy class manually or use a library like the Duck Typing Project to emit a proxy class at runtime.
Both will have the same result: you will have a class that implements the interface, and proxies all calls to the static methods of the static class. Whether you want to write this yourself or use the duck typing library is up to you.
EDIT: Thomas' answer of using a singleton would be the way to go, if you have that option.
Static classes can't implement interfaces--it really wouldn't make much sense. An interface provides a standard API that all instances will support and you can swap instances and polymorphically access the methods through the standard interface. With a static class, all references to it are through the class anyways.
Typically in this situation you want a factory to support DI of an instance class that implements your helper.
public interface IHttpHelper
{ }
public class RealHttpHelper
{ ... }
public class FakeHttpHelper
{ ... }
public static class HttpHelper
{
public static IHttpHelper Instance
{
get
{
return whatever ? new RealHttpHelper() : new FakeHttpHelper();
}
}
}
...
HttpHelper.Instance.Context...
...

Categories

Resources