I have a static class that gets me a client..
public static ClientFactory {
private static Lazy<IClient> _MyClient;
public static IClient GetClient(ICache cache) {
if (_MyClient == null) {
_MyClient = new Lazy<IClient>(() => CreateClient(cache));
}
return _MyClient.Value;
}
private static IClient CreateClient(ICache cache) {
// code that takes 1-2 seconds to complete
return new Client(cache);
}
}
Is there any chance that I can have 2 or more clients created by writing code like this? Where the second client would overwrite the first one?
How should I update my code in a way, such that the constructor is called only once per application?
Thanks.
Is there any chance that I can have 2 or more clients created by writing code like this?Yes.Lazycaches exceptions, which is very unlikely to be the behaviour you want. So ifCreateClienthas any possibility of throwing an exception you should consider using stackoverflow.com/a/42567351/34092 .