简体   繁体   中英

Holding a class instance in a Static object in C#

We have a class " DataAccessServiceConnector ", in which we have few methods to communicate with Data Access Service.

public class DataAccessServiceConnector: IDataAccessServiceConnector
{
     public async Task<HttpResponseMessage> GetDataAccessServiceResponse()
     {
        //Some code
        return GetDataFromDataAccessService();
     }        
}

We have an Interface:

public interface IDataAccessServiceConnector
{
    Task<HttpResponseMessage> GetDataAccessServiceResponse();
}

And having a different class, that is holding the instance of "DataAccessServiceConnector" class in the as static object.

public class ClassA
{
  public static IDataAccessServiceConnector DataAccessConnector;
  //Constructor of the Class
  ClassA()
  {
     DataAccessConnector = DataAccessConnector ?? new DataAccessServiceConnector();
  }
}

Is it bad practice to hold the class instance (ie DataAccessServiceConnector ) in a static object(ie DataAccessConnector )?

I think, the answer to your question is opinion-based in context of StackOverflow.

This is a classic "Is Singleton Pattern Bad?" question:


There are numerous issues with Singletons in particular and with shared-write-access memory in general.

  • As others mentioned above, sharing resources requires extreme caution;
  • Similarly, [unit] testing of such class is not easy;
  • The (inter)dependencies between classes are less discoverable;
  • The code is harder to follow;
  • The bugs are harder to fix;
  • Code refactoring becomes harder in certain cases;
  • ...this list goes and goes on.

I personally decided to use Singletons as a last resort solution only. Even then, I would rely on a dependency injection framework's singleton registration instead of a static field. (Eg SimpleInjector's singleton registration .)

But before registering something as a Singleton, please reconsider using regular objects first.

Option 1.

If there is already a top level object such as 'Program' or 'Application' that everyone already has access to, you can make the instance object a new field or property on it.

Option 2.

Provide static access to the instance object, from the instance object, as a static method/field/property.

Or, as you have described, provide static access to the instance object from some other arbitrary type, if doing so is convenient for your design. The class heirarchy as you have described it sounds perfectly normal to me, actually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM