I have created an .NET Core API project. It works but it creates a new object for each get request. Where can I save the object so that I can reuse it? I have searched Google and found Session but that only seems to store bytes or serialised bytes. I don't think I can serialise the object.
If doSomeInitialisation() takes 1 seconds, creating a new SomeLibrary at each get request when the arg1 is the same does not seem efficient and SomeLibrary is not serialisable so it cannot be stored to the Session.
[HttpGet("{arg1}/{arg2}")]
public IActionResult Get(string arg1, string arg2)
{
var someLibrary = new SomeLibrary();
someLibrary.doSomeInitialisation(arg1);
return someLibrary.doSomething(arg2);
}
Requests
httpx://..../dog/1
httpx://..../dog/2
httpx://..../dog/3
httpx://..../cat/1
httpx://..../cat/2
I could reuse the same SomeLibrary object for the first three requests.
I suppose you use DI in your project. First of all read this article Dependency injection in ASP.NET Core. Then you'll realize that you can use following code to register only one instance per application:
//Startup.cs
services.AddSingleton<ISomeLibrary>(new SomeLibrary());
....
//controller
public SomeController : Controller
{
private readonly ISomeLibrary _sl;
public SomeController(ISomeLibrary sl)
{
_sl = sl;
}
...
}
UPDATE:
According to your last comment you can implement it like this:
public interface ISmthResolver
{
ISomeLibrary Get(string arg);
}
...
public class SmthResolver : ISmthResolver
{
private readonly ConcurrentDictionary<string, Lazy<ISomeLibrary>> _instances = new ConcurrentDictionary<string, Lazy<ISomeLibrary>>();
public ISomeLibrary Get(string arg) => _instances.GetOrAdd(arg, key => new Lazy<ISomeLibrary>(() => new SomeLibrary())).Value;
}
...
services.AddSingleton<SmthResolver, ISmthResolver>();
...
public class Some
{
public Some(ISmthResolver sr)
{
var sl = sr.Get("arg");
}
}
Also read this Making ConcurrentDictionary GetOrAdd thread safe using Lazy.
You can try on singleton pattern,but you should be considering that if it fits your demands because singleton pattern is not a good way for all classes.
public class Singleton
{
private static string _locker = new object();
private static Singleton _instance = null;
public string SerializedString="";
///Constructore is called just one time !
public Singleton(arg1){
DoSerialization(arg1);
}
public static Singleton Instance
{
get
{
if (_instance == null)
{
lock (_locker)
{
if (_instance == null)
{
_instance = new Singleton();
}
}
}
return _instance;
}
}
private void DoSerialization(arg1){
this.SerializedString=JsonConvert.SerializeObject(arg1)
}
}
and use it like this
var SameInstance=new Singleton(arg1).Instance;
var serialized=SameInstance.SerializedString;
Related
Just recently started to try and learn some designs patterns. Currently trying to get my singleton to return a new object. However it keeps throwing the error "Cannot convert method group 'getInstance' to non-delegate type 'MainWdinow.CustomerLoader'. did you intend to invoke the method?
here is the code for the design pattern method
public class CustomerLoader
{
private static Customer firstInstance = null;
public static Customer getInstance()
{
if(firstInstance ==null)
{
firstInstance = new Customer();
}
return firstInstance;
}
}
Here is where I try to call the method and I get the error mentioned above
CustomerLoader t = CustomerLoader.getInstance();
I want my singleton to do the job of the code below and create a new instance of the customer object
Customer T = new Customer;
Use this. It's also thread safe unlike your version
private static readonly Lazy<Customer> _instance = new Lazy<Customer>(() => new Customer());
public static Customer Instance => _instance.Value;
But you should really use dependency injection instead singletons.
And your naming is off, it looks like Java, check this https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-type-members
private members are not covered by guidelines. But even Microsoft uses _camelCase for private fields in corefx https://github.com/dotnet/corefx/blob/master/Documentation/coding-guidelines/coding-style.md
Use this example:
public class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Singleton should be about one class, not three.
Be careful with it cause your implementation is not thread-safe. See this padlock variable here. It prevents creating multiple instances in a multi-treaded applicatoins.
CustomerLoader.getInstance
Is a function, you cant assign it to
CustomerLoader
Your code should look more like that:
class Train
{
protected Train() { }
protected static Train instance;
public static Train GetSingeltonInstance()
{
if(instance == null)
{
instance = new Train();
}
return instance;
}
}
class TainUser
{
private readonly Train train;
public TainUser()
{
train = Train.GetSingeltonInstance();
}
}
Am I able to use an instance of once class in another class and file without having to reinstantiate it?
class Start
{
public static Log Log = new Log(...);
}
class Start1
{
Log.Write("New instance!");
}
I have read about having to use a get/set block to do it, but I'm not exactly sure how I would go about that,
Singleton pattern:
public class Log
{
private static Log instance;
private Log() { }
public static Log Instance
{
get
{
return instance ?? (instance = new Log());
}
}
}
Use it by calling Log.Instance, and so on.
To call this using a parameter, you need to do something like this:
public class Log
{
private string foo;
private static Log instance;
public static Log Instance
{
get
{
if (instance == null)
{
throw new InvalidOperationException("Call CreateInstance(-) to create this object");
}
else
{
return instance;
}
}
}
private Log(string foo) { this.foo = foo; }
public static Log CreateInstance(string foo)
{
return instance ?? (instance = new Log(foo));
}
}
However, it is generally a bad idea to use singletons in this manor. Have a look at dependency injection / inversion of control to see how this can be solved.
I have been playing around with ways to implement Singletons. I have written a little management object that allows for a easier, less code approach to writing singleton classes.
I would never use something like this in a production system for a couple of reason which lead me to my question.
With the below code - I am assuming that this implementation would/could lead to both threading issues and memory leaks? Would I be correct?
namespace ConsoleApplication1
{
public static class SingletonManager
{
private static readonly Dictionary<string, object> Objects;
static SingletonManager()
{
Objects = new Dictionary<string, object>();
}
public static T InstanceOf<T>(object[] ctorArgs = null)
where T : class
{
var name = typeof (T).FullName;
if (Objects.ContainsKey(name))
return Objects[name] as T;
var ctor = typeof (T).GetConstructors(
BindingFlags.Instance |
BindingFlags.NonPublic)[0];
var instance = ctor.Invoke(ctorArgs) as T;
Objects[name] = instance;
return instance as T;
}
public static void DisposeOf<T>()
where T : Singleton<T>
{
Dispose(typeof (T).FullName);
}
public static void DisposeOf(Type type)
{
Dispose(type.FullName);
}
private static void Dispose(string name)
{
if (!Objects.ContainsKey(name)) return;
var obj = Objects[name];
if (obj is IDisposable)
((IDisposable) Objects[name]).Dispose();
Objects.Remove(name);
}
}
public class Singleton<T>
where T : class
{
private static object ThreadLock = new object();
public static T Instance(object[] ctorArgs = null)
{
lock (ThreadLock)
{
return SingletonManager.InstanceOf<T>(ctorArgs);
}
}
}
public class SomeSingletonClass : Singleton<SomeSingletonClass>
{
public int Number;
private SomeSingletonClass(int i)
{
Number = i;
}
}
internal class Program
{
private static void Main(string[] args)
{
var instance1= SomeSingletonClass.Instance(new object[] {1});
var instance2 = SomeSingletonClass.Instance(new object[] { 2 });
//Is false
var updated = instance1.Number == 2;
instance2.Number = 99;
//Is true
var equals = instance1.Number == instance2.Number;
//Is true
var refEquals = ReferenceEquals(instance1, instance2);
Debugger.Break();
}
}
}
Classical singletons are very rarely a good idea. In most cases you're better off with simply creating a single instance which you pass to the code that needs it, instead of enforcing that there is only one. An IoC container will do most of that work for you.
An implementation of a classical singleton is quite compact, no need to simplify it further:
public class MySingleton
{
private static Lazy<MySingleton> _instance = new Lazy<MySingleton>(() => new MySingleton());
public static MySingleton Instance { get { return _instance.Value; } }
private MySingleton()
{
}
}
At best you can save two of these lines.
Yes, your code is not thread safe. You'd need to put most of it in lock statements to fix that.
The consumer determining the constructor parameters is very dubious. Unless all of them are identical, you'll end up with different instances, depending on which consumer runs first.
This violates the "single source of truth" principle and is a maintenance and debugging nightmare.
Your code relies on private reflection.
I realized that I should have only one instance of an object called StdSchedulerFactory running at a time. So far I instantiated the object like this
StdSchedulerFactory sf = new StdSchedulerFactory(properties);
And properties is a NameValueCollection.
How can I write a Singleton class for this object so that the variable sf will always have one instance throughout the program?
Part of the Singleton pattern is typically a private constructor, so that other classes can not make new instances.
The workaround for parameters coming from outside the class is to add a "Init" or "Configure" function:
public static void Configure(NameValueCollection properties)
{
}
Of course, if you forget to call this function, you may get behavior you don't want; so you may want to set a "Configured" flag or something like that so your other functions can react appropriately if this function has not yet been called.
Here is a basic Singleton implementation. It is not thread-safe.
public sealed class StdSchedulerFactory
{
private static readonly StdSchedulerFactory instance;
private NameValueCollection _properties;
private StdSchedulerFactory(NameValueCollection properties)
{
_properties = properties;
}
public static StdSchedulerFactory GetInstance(NameValueCollection properties)
{
if (instance == null)
{
instance = new StdSchedulerFactory(properties);
}
else
{
return instance;
}
}
}
this is my two favorite way implementing simple singleton pattern. The second one is just easier when debugging :)
public sealed class SingletonOne
{
private static readonly Lazy<SingletonOne> instance = new Lazy<SingletonOne>(() => new SingletonOne());
private Lazy<Controller> controller = new Lazy<Controller>(() => new Controller(properties));
private static object properties = null;
public static SingletonOne Instance { get { return instance.Value; } }
public Controller GetController(object properties)
{
SingletonOne.properties = properties;
return this.controller.Value;
}
}
public sealed class SingletonTwo
{
private static readonly SingletonTwo instance = new SingletonTwo();
private Controller controller;
private static object properties = null;
public static SingletonTwo Instance
{
get
{
return SingletonTwo.instance;
}
}
public Controller GetController(object properties)
{
SingletonTwo.properties = properties;
if(this.controller == null)
{
this.controller = new Controller(SingletonTwo.properties);
}
return this.controller;
}
}
public class Controller
{
public Controller(object properties) { }
}
I have a number of classes doing different things but using the same Singleton pattern from http://www.yoda.arachsys.com/csharp/singleton.html
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Does anyone have a neat way I can reuse as much of the common Singleton code as possible between the different classes?
For example if I have SingletonJob1 and SingletonJob2 I'd like to be able to change the code in only place if I move to one of the other Singleton patterns.
Edit: Yes as people have pointed out Method 5 from http://www.yoda.arachsys.com/csharp/singleton.html is less code. I did read to the end of the page! I chose method 2 because the Singleton objects relate to hardware devices and I want only want a couple of them initialised and used in any given run of the program. Method 5 will initialise them all straight away.
Is there any reason you're using that version rather than the simpler one which just initializes the instance in the declaration?
public class Singleton
{
private static Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
// Only use this if you really need it - see the page for details
static Singleton() {}
private Singleton()
{
// I assume this logic varies
}
}
This pattern is sufficiently short that I don't think it's much of a problem to include it everywhere.
I would urge you to consider whether you really need that many singletons; they're generally not great for testability etc.
EDIT: If you really, really want laziness and you're using .NET 4, you can get it with the 6th pattern which is on the singleton page's new home:
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
public static class Singleton<T> where T: new()
{
static T instance=null;
static readonly object padlock = new object();
public static T Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new T();
}
return instance;
}
}
}
}
So you can use your Singleton for all Classes:
Singleton<YourClass>.Instance.YourMethod();
Try take a look at:
http://www.codeproject.com/KB/architecture/GenericSingletonPattern.aspx
Something like this?
public sealed class Singleton<T>
{
static T instance=null;
static readonly object padlock = new object();
static Func<T> createInstance;
Singleton(Func<T> constructor)
{
createInstance = constructor;
}
public static T Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = createInstance();
}
return instance;
}
}
}
}
I believe this is what you are after. However I strongly recommend avoiding this Singleton (capital S) pattern as it crushes all unit testing souls and makes heaps of things difficult to control.
public class Singleton<T> where T : new()
{
private static T _Instance;
private static readonly object _InstanceLock = new object();
public static T Instance
{
get
{
if (_Instance == null)
{
lock (_InstanceLock)
{
if (_Instance == null)
{
_Instance = new T();
}
}
}
return _Instance;
}
}
}
public class Foo : Singleton<Foo>
{
public void Something()
{
}
}
public class Example
{
public static void Main()
{
Foo.Instance.Something();
}
}