Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is anything wrong with using static readonly references for a service class?

Tags:

c#

oop

asp.net

soa

I have inherited this piece of code, and the original author for some reason really liked static readonly references.

I have outlined the general pattern below, what ramifications does having these static readonly references have?

public class DbAccess
{
    private static readonly ISomethingFactory = SomethingFactories.GetFactory("1");
    private static IThing1Dao Thing1Dao { get {return ISomethingFactory.Thing1Dao; }}
    private static IThing2Dao Thing2Dao { get {return ISomethingFactory.Thing2Dao; }}
}

public class SomethingFactories
{
   public static ISomethingFactory GetFactory(string key) 
   {
      switch(key)
      {
         case "...":
         return new SomeFactory();
      }
   }
}    

public class SomeFactory : ISomeFactory
{    
    public IThing1Dao Thing1Dao
    {
       get { return new Thing1Dao(); }
    }
}    

public class SomeService : ISomeService
{
    private static readonly IThing1Dao thing1Dao = DbAccess.Thing1Dao
    private static readonly IThing2Dao thing2Dao = DbAccess.Thing2Dao

    public Thing1Object1 GetObject1(int id)
    {
        return thing1Dao.GetObject1(id);    
    }

    public Thing1Object2 GetObject2(int id)
    {
        return thing1Dao.GetObject2(id);
    }
}

The usage in the .aspx pages is like:

public class MyBasePage : System.Web.UI.Page
{
    protected static readonly SomeService someService = new SomeService();     
}    

public class SomeAspxPage : MyBasePage
{
   void btnAddObject1(...)
   {
      Thing1Object1 obj1 = someService.GetObject(1);
   }
}
like image 274
loyalflow Avatar asked Jan 29 '26 19:01

loyalflow


1 Answers

static means that only one instance of ISomethingFactory exists, and that instance can be accessed through the type (not one instance per instance of DbAccess).

readonly means that, after initialization, the value cannot be overwritten.

This is a fairly normal pattern for performing initialization based on startup-time data (e.g. data from app.config).

like image 168
Eric J. Avatar answered Feb 01 '26 10:02

Eric J.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!