Is my implementaton of HttpClient singleton appropriate? [closed] - c#

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 9 years ago.
Improve this question
I am using System.Net.HttpClient (.Net 4.5) in my MVC4 project. I know that a single instance of HttpClient can be used for all Http requests across the web app. Here is my implementation of the HttpClient singleton which should return the single instance every time.
public sealed class HttpClientInstance: HttpClient
{
// singleton instance
private static readonly HttpClientInstance instance = new HttpClientInstance();
static HttpClientInstance() { }
private HttpClientInstance() : base() {
Timeout = TimeSpan.FromMilliseconds(15000)));
}
/// <summary>
/// Returns the singleton instance of HttpClient
/// </summary>
public static HttpClient Instance
{
get
{
return instance;
}
}
}
Do you see any issues with this?
I know I could possibly use Ninject to inject the dependency in singleton scope but that is besides the point.

There are a few properties that you cannot change after you have made the first request. I think timeout might be one of them, so be aware of that.
You also need to be careful that individual requests don't mess with the DefaultRequestHeaders as that could confuse other requests.
It is always a good idea to try and share HttpClient instances. Creating a singleton is an extreme case of that but with care it should work just fine for you.

Related

ASP.NET Core - Any reason not to use a parameter object with dependency injection? [closed]

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 3 years ago.
Improve this question
I like the DI feature of ASP.NET Core, but am finding that some of my classes end up with huge constructor parameter signatures...
public class Foo {
private IBar1 _bar1;
private IBar2 _bar2;
// lots more here...
public Foo(IBar1 bar1, IBar2 bar2, lots more here...) {
_Bar1 = bar1;
_Bar2 = bar2;
// ...
}
public DoSomething() {
// Use _bar1
}
}
In case this looks like a code smell, it's worth pointing out that any controller is going to use AutoMapper, an email service and 2 or 3 managers related to ASP.NET Identity, so I have 4 or 5 dependencies before I start injecting a single repository. Even if I only use 2 repositories, I can end up with 6 or 7 dependencies without actually violating any SOLID principles.
I was wondering about using a parameter object instead. I could create a class that has a public property for every injected dependency in my application, takes a constructor parameter for each one, and then just inject this into each class instead of all the individual Bars...
public class Foo {
private IAllBars _allBars;
public Foo(IAllBars allBars) {
_allBars = allBars;
}
public DoSomething() {
// Use _allBars.Bar1
}
}
The only disadvantage I can see is that it would mean that every class would have every dependency injected into it via the parameter object. In theory, this sounds like a bad idea, but I can't find any evidence that it would cause any problems.
Anyone any comments? Am I letting myself into potential trouble by trying to make my constructor code neater?
What you're describing sounds like the service locator pattern, and while it seems tempting to simplify your code by eliminating all those constructor parameters, it usually ends up hurting maintainability in the long run. Check out Mark Seemann's post Service Locator violates encapsulation for more details about why it should be avoided.
Generally, when you find yourself with a class with dozens of constructor parameters, it means that class might have too many responsibilities. Can it be decomposed into a number of smaller classes with narrower goals? Rather than introducing a "catch-all" class that knows about everything, maybe there's a complex part of your application that you can abstract behind a facade.
Sometimes, you do end up with large coordinator classes that have many dependencies and that's okay in certain circumstances. However, if you have many of these it's usually a design smell.

Making an object public static vs passing it around [closed]

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 5 years ago.
Improve this question
I am writing a game in Monogame framework and well
there are some objects that have only 1 instance
(but that does not necessarily mean that there should be only 1
instance) during the lifespan of an application by default,
like for example ContentManager.
Now what's bugging me is that I am not sure what is a better practice and why:
To make that object public static and access it from other classes
to use that static instance to load stuff
or
Pass that object as an argument to other classes constructor and use it that way
Just to add another option, you can use the singleton pattern to restrict the creation of new classes, like a GameManager. This pattern comes with cons and pros, so you need to analyze your requirements.
public final class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
The simplest way to implement the implement the pattern is to have a class with a private constructor, a static parameter for your instance and a method to return the instance.
https://en.wikipedia.org/wiki/Singleton_pattern

Trying to properly organize huge class [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have huge class that implements usage of some client:
public class Client : IClient
{
internal Client(string username, string password){
//login process here
}
//some private methods that make sure connection stays alive, etc
public void Action1(string param1){
//something here...
}
public void Action2(string param1, string param2){
//something else here...
}
}
As it currently is, it's 5000+ lines long mainly because of lots of different public methods.
I'm wondering what is the best practice to properly organize and refactor this, preferably without making method calls more complicated?
Use partial classes and group things into logical sets per each partial class.
Also, if some methods make logical set, consider wrapping them into separate class.
Those 2 should reduce your lines of code per file dramatically.
Usually big class are "hiding" inside other classes (see uncle Bob on "Clean Code").
In your case I'd split the class creating Action classes and making some machanics that lets the Client use some sort of IAction or BaseAction. Thus splitting the logic of every action into a separate class.
To be more precise I'd rather need some more info and code.

One object for whole application life or one object per call + dispose [closed]

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 6 years ago.
Improve this question
I have an IDisposable class A. I need to use an object of A inside another method M of class B. Method M is called multiple times (million times a day). Should I use local object of A inside M and dispose once done or should I declare class level static member inside B and dispose once application ends.
Let me know if I am not clear.
One object for the life of the application is a Singleton; while they are useful under specific circumstance, they are not generally a good idea. See this question for a detailed explanation of why.
Classes that implement IDisposable are best used within the confines of a using statement that will take care of disposing it for you.
The clear exception to this is when multiple calls to the disposable class will be needed in the context of a single business action -- and that action is too spread out to be wrapped in a using statement. In this case, wrapping all the calls into a second disposable class that has the first as a private member. when the second class is disposed it should dispose of any private members that are disposable.

Real life usage of Singleton and Static class c# [closed]

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 8 years ago.
Improve this question
i do not want to know the difference between singleton and static class first of all.
i like to know when people should use singleton class and when static class.
in my apps i use static class for helper or utility method and use singleton for db connection and error logger class. but with the help of static class can be used to return sql db connection object and as well as error logging system.
i really like to know about other senior developer where they use singleton class and where they use static class.
it will very helpful if some one discuss this matter with sample situation and sample code. thanks
If you are creating loosely coupled system, then there is no way you can use static classes (because they cannot implement abstraction and cannot be injected). Static classes also very hard to mock, so it's not your choice if you are doing TDD or simple unit-testing. So, I use them only for dependencies which are not related to business requirements and should not be mocked. E.g. infrastructure logic like logging or mapping.
I also use static classes for extension methods if I cannot extend existing class, but want handy member-like API. Usually this is a also infrastructure-related extensions, like mapping, or serialization, which do not contain business logic.
A very broad question but will give you the first reason that popped into my head for use of a Singleton.
A Singleton is more appropriate than a dedicated static class when you need to manage the lifetime of some cached objects. Singletons are perfect when you want to refresh state without having to worry about thread safety, for example if you have a class that is being used as a singleton and it has many cached properties or lists that incoming requests may want access to.
The Refresh() method can simply be setting the current instance to a new instance and not having to refresh individual properties of the class:
private static YourClass instance = new YourClass(); // first instance
public static void Refresh(){
instance = new YourClass(); // creates a new, refreshed instance while not needing to worry about thread safety
}
public static YourClass Instance{
get{
return instance;
}
}
I usually use singleton classes when I am creating a database access object. Where I can have the instance of the object anywhere inside an application.
I usually stay away from static classes, which the exception of an occasional loader class when loading particular assets.

Categories