Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton replacement?

Tags:

c#

singleton

In my senario, I have a global setting object, say GlobalSettings, it has a static property "Current" (singleton), and there should be only one GlobalSettings instance.

But...In my data model, there's an entity "LocalizedContent":

public class LocalizedContent {
     public string Title { get; set; }
     public string Content { get; set; }
     public string CultureName { get; set; }
}

In the constructor, I want to initialize the instance by setting CultureName to default culture of the system, and I can get the default culture name from GlobalSettings.Current.DefaultCultureName.

However, I don't want to use the singleton property "GlobalSettings.Current" in LocalizedContent class, since it will result in strong-coupling. So my question is, where is the right place to set this default culture name?

Thanks in advance!

like image 639
Mouhong Lin Avatar asked Sep 04 '26 11:09

Mouhong Lin


2 Answers

Why not add a constructor to LocalizedContent that takes the DefaultCultureName as a parameter?

LocalizedContent can then be re-used without a dependency on GlobalSettings.

like image 186
Philip Fourie Avatar answered Sep 07 '26 01:09

Philip Fourie


I think the trick here is to add a constructor to the LocalizedContent class which takes in the values it needs to consume.

public LocalizedContent {
  public LocalizedContent(string cultureName) {
    this.CultureName = cultureName;
  }
}

For convenience sake you could also add a helper method which creates the LocalizedContent method using the GlobalSettings values.

public static LocalizedContent CreateLocalizedContent() {
  return new LocalizedContent(GlobalSettings.Current.DefaultCultureName);
}
like image 33
JaredPar Avatar answered Sep 07 '26 01:09

JaredPar



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!