I want to implement a class whose instance is global but whose property is to be initialized only once during the run time.
Also the initialization is to be done as an assignment from a result of function during execution.
Basically I want to do something like this
public class Configuration
{
public string param1 { get ; set; }
public int param2 { get; set; }
}
public static class AppConfig
{
public static readonly configuration;
}
public class Initialize
{
public void InitConfig()
{
AppConfig.configuration = GetParamsFromDB();
}
}
But I am unable to figure out how to implement it. Please ignore the above incorrect representation. It is just to present what is required.
EDIT
Also there is a need of seperate class Initialize because classes Configuration and AppConfig are in dll BO. GetParamsFromDB() is in DAL. DAL references BO hence
BO cannot refere DAL hence GetParamsFromDB() cannot be used within AppConfig class
All you need to do is initialize it inline:
public static class AppConfig
{
public static readonly configuration = GetParamsFromDB();
}
The C# runtime will automatically ensure that the parameter isn't initialized until the class is accessed for the first time, giving you your desired behvaior.
Note that your configuration type is mutable, which if you want to ensure these values aren't changed, is a bad thing. You should refactor your configuration class to accept the two values in its constructor and not provide public setters for the properties.
It looks like you want a singleton.
See: Implementing the Singleton Pattern in C#
public static class AppConfig
{
private static readonly Lazy<Configuration> _configuration = new Lazy<Configuration>(() => new Configuration());
public static Configuration Instance { get { return _configuration.Value; } }
}
However, you should consider changing your design as singletons are often overused.
Consider something that can be used with dependency injection and inversion of control.
Dependency injection is a pattern that increases code reuse and minimize dependencies through interfaces.
Inversion of control is a pattern that binds objects together at runtime typically using an assembler object.
Example:
public interface IAppConfig
{
Configuration Configuration { get; }
}
public sealed class AppConfig : IAppConfig
{
private readonly Configuration _configuration;
public AppConfiguration()
{
_configuration = new Configuration { };
}
public Configuration Configuration { get { return _configuration; } }
}
This can be used together with an IoC Container to provide configuration to all the objects that need it.
What you are trying to do is kind of Singleton Pattern, It can be implemented as follows,
public sealed class Configuration
{
private static volatile Configuration instance;
private static object syncRoot = new Object();
private Configuration() {}
public static Configuration Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Configuration();
}
}
return instance;
}
}
}
Related
I have a bit of a problem and am not sure how to go about solving this. I have two classes named DatabaseManagment and Logger that reference each other. But, I get a stackoverflow error due to an endless recursion. Since I am creating an instance of Logger in DatabaseManagement as well as creating an instance of DatabaseMangement within the Logger class, the program just endlessly goes between each class until it fails. I have put code samples below. Both classes are dependent on one another for their functionality. How can each class reference the other without the recursion?
DatabaseManager
class DatabaseManagement
{
Logger l = new Logger();
public MySqlConnection myconn { get; private set; }
public void OpenDatabases()
{
Logger
class Logger
{
DatabaseManagement dm = new DatabaseManagement();
public void createLogEntry(char logType, string message)
{
I'm thinking this should do the trick.
Neat thing: no statics.
Only real 'trick' you need to do is pass this (the instance of the current object, in this case the instance of DatabaseManagement) to the constructor of Logger.
class DatabaseManagement
{
private Logger _logger;
public DatabaseManagement()
{
_logger = new Logger(this);
}
}
class Logger
{
DatabaseManagement _dm;
public Logger(DatabaseManagement dm)
{
_dm = dm;
}
}
This should solve your problem:
public class DatabaseManagement
{
Logger logger;
// Other properties and fields
public DatabaseManagement()
{
this.logger = new Logger(this);
// Other constructor stuff
}
// Other methods
}
public class Logger
{
DatabaseManagement dbManagement;
// Other properties and fields
public Logger(DatabaseManagement dbManagement)
{
this.dbManagement = dbManagement;
// other constructor stuff
}
// Other methods
}
And FYI, this pattern is called Constructor Injection.
You could also use a property to get a singleton whenever you need to use / call one of your classes:
class DatabaseManagement
{
private static DatabaseManagement _instance;
public static DatabaseManagement Inst {
// Return _instance, but make it a new DatabaseManagement() if null:
get { return _instance ?? (_instance = new DatabaseManagement())}
}
...
}
class Logger
{
private static Logger _instance;
public static Logger Inst {
get { return _instance ?? (_instance = new Logger())}
}
...
}
Now you can call either of these from pretty much anywhere as follows, and know that you'll always be using a single instance:
Logger.Inst.SomeMethod();
DatabaseManagement.Inst.SomeMethod();
I have implemented an interface IService that inherits functionality from a series of other interfaces and serves as a common ground for many different services.
Each of these services is being described by an interface, for example:
public interface IServiceOne : IService
{
//...
}
public class ServiceOne : IServiceOne
{
//...
}
Everything up to that point works as expected:
IServiceOne serviceOne = new ServiceOne();
IServiceTwo serviceTwo = new ServiceTwo();
What I have to do now is to add a big list of constants (public variables) to each of these services which will however be different as per service type (for example, IServiceOne will have different constants than IServiceTwo, there will be constants in IServiceOne that will not exist in IServiceTwo, etc).
What I'm trying to achieve is something like that:
IServiceOne serviceOne = new ServiceOne();
var someConstantValue = serviceOne.Const.SomeConstant;
Just because the variables will differ as of service type I decided to implement an extra interface for each of them:
public interface IServiceOneConstants
{
//...
}
and then broaden my IService definition:
public interface IServiceOne : IService, IServiceOneConstants
{
//...
}
public class ServiceOne : IServiceOne
{
//...
}
The problem I have now is that I don't know how to implement the concrete class for IServiceOneConstants. Obviously by the time one of its variables (we called them constants here) will be called it has to be instantiated, so initially I though of a static class but then you cannot expose a static class's functionality through an interface. I then tried to do it with a singleton and expose its instance via a public non-static wrapper:
public class Singleton : IServiceOneConstants
{
private static Singleton _instance;
private Singleton()
{
SomeConstant = "Some value";
}
public static Singleton Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
public String SomeConstant { get; set; }
public Singleton Const
{
get
{
return Instance;
}
}
}
I then adjusted the IServiceOneConstants like that:
public interface IServiceOneConstants
{
Singleton Const { get; }
}
but when I call this:
IServiceOne serviceOne = new ServiceOne();
var someConstantValue = serviceOne.Const.SomeConstant;
I get a null reference exception, as .Const is null.
What am I missing here?
You really helped yourself to get confused as possible, by naming different stuff same name ;)
So, first...
what you're trying to do is to access singleton instance through instance property:
public Singleton Const
{
get
{
return Instance;
}
}
then you are using it like:
serviceOne.Const
but that variable was never assigned. In order to assign it, you should make an instance of Singleton class, assign it to serviceOne.Const property and then you might use it.
What you need is probably something like this:
public class ServiceOne : IServiceOne
{
public Singleton Const
{
get
{
return Singleton.Instance;
}
}
}
You need to check to see if the singleton has been instantiated in ServiceOne.Const.SomeConstants` getter. If it's not, you need to instantiate it. Then return the value of the constant.
On a ASP.NET MVC application with multiple assemblies I need to access a few settings.
Basically. the settings are constants or values from Web.Config AppSettings.
My idea is to inject a Settings class, as a singleton, in places where I need it:
public interface ISettings {
LoggerSettings Logger { get; }
} // ISettings
public class LoggerSettings {
public String Levels { get { return ConfigurationManager.AppSettings["Logger.Levels"]; } }
public const String Report = "team#xyz.com";
} // LoggerSettings
public class Settings : ISettings {
public LoggerSettings Logger { get; private set; }
public Settings() {
Logger = new LoggerSettings();
}
} // Settings
What do you think about this approach and injecting the class as a singleton?
Do I need, in this case, to set any class/property as static?
I think I need to have LoggerSettings and its properties as static, not?
Otherwise I will need to create a new instance when constructing the Settings?
Could someone, please, advise me on this?
If you are actually injecting your class (via a DI framework), and by "singleton" you mean you are using a singleton "scope" in your DI framework, then this approach will work just fine. If this in fact what you are doing, then none of your properties need to be static, as the same "singleton" instance will be injected into any class that depends on it.
several classes in my dll require a set of the data ( general configurations ) . these data are provided by the one who uses the dll through implementing an interface IConfigs . so data should be injected as a dependency . now I wonder how to do that .
Update :
sorry , if the question was not clear . the problem is should I have an instance of IConfigs in each class that needs it and using constructor injection ( that I don't like this approach ) or there is a cleaner way to handle this situation ?
You can use injection dependency by property.
If you use MEF :
Service
[Export(typeof(IServiec))]
public class Service : IService
{
....
}
Client
public class Client
{
[Import]
public IService Service
{
}
}
Nota : You add lines in order to register your catalog and container
If I understand you correctly, you want do register different derived classes with one interface, don't know what IoC Container you uses, but in here I uses Unity as in sample code, but most of other IoC Containers support using one string to differentiate registration in one interface. Assume you have:
public interface IConfig {}
public class ConfigA : IConfig {}
public class ConfigB : IConfig {}
So you can register both ConfigA and ConfigB to IConfig with different name:
var container = new UnityContainer();
container.RegisterType<IConfig, ConfigA>("A");
container.RegisterType<IConfig, ConfigA>("B");
public class MainClass
{
private IConfig _config;
public MainClass([Dependency("A")] IConfig config)
{
_config = config;
}
}
If you don't want to use constructor dependency, use property:
public class MainA
{
[Dependency("A")]
private IConfig Config { get; set; }
}
As your helper classes are static, you won't be able to use DI unless you use a ServiceLocator style and have your helper class retrieve injected values itself, something like this:
public static class HelperClass
{
static HelperClass()
{
var config = ServiceLocator.Get<IConfig>();
UserId = config.Get("UserId");
}
public static int UserId { get; private set; }
}
This is not considered good practice because your helper class then has a hidden dependency on your ServiceLocator being set up with an IConfig which contains a UserId.
I'd therefore recommend you change your helper class to be non-static, and have the IConfig it needs injected into it via its constructor, like this:
public class HelperClass
{
public HelperClass(IConfig config)
{
UserId = config.Get("UserId");
}
public int UserId { get; private set; }
}
You can then inject your HelperClass into your service classes via their constructors, like this:
public class ServiceClass
{
private readonly HelperClass _helperClass;
public ServiceClass(HelperClass helperClass)
{
_helperClass = helperClass;
}
}
This way each component can be swapped out, stubbed or mocked as necessary. If your HelperClass has no state of its own you can configure your DI container to manage it with a Singleton lifetime, which essentially makes it 'static' with none of the disadvantages.
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!
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.
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);
}
Hm, you may wish to check this out.
In short, what you would like to do is, inject a "culture" source into your localized content object. Consider the following example,
// your public global settings singleton, no big surprises here
// except possibly thread safe locking [shrug] if you are singlethreaded
// you can simplify this model further
public class GlobalSettings
{
// singleton synchronization and instance reference
private static readonly object _instanceSyncRoot = new object ();
private static readonly GlobalSettings _instance = null;
// instance-based synchronization and values
private readonly object _syncRoot = new object ();
private string _cultureName = string.Empty;
// gets public static instance
public static GlobalSettings Current
{
get
{
lock (_instanceSyncRoot)
{
if (_instance == null)
{
_instance = new GlobalSettings ();
}
}
return _instance;
}
}
// gets public culture name
public string CultureName
{
get { lock (_syncRoot) { return _cultureName; } }
set { lock (_syncRoot) { _cultureName = value; } }
}
// private constructor to re-inforce singleton semantics
private GlobalSettings () { }
}
So, a number of things. Typically singletons like this are frowned upon - they are very convenient! but as you point out, lead to tight-coupling between functional components and configuration.
If you would like to move away from this tight coupling, while preserving what exists, you have a few options, easiest being
// define a general-purpose settings interface, i do not much
// care for refactor tools, but you may use re-sharper or built in
// refactor components to "extract" those properties from global
// settings that you need. here we pull out culture name only,
public interface ISettings
{
// gets culture name from underlying settings implementation
string CultureName { get; }
}
public class LocalizedContent
{
public string CultureName { get; set; }
public LocalizedContent (ISettings settings)
{
CultureName = settings.CultureName;
}
}
If you are able to modify GlobalSettings singleton,
// public singleton is now an implementation of a "loosely coupled
// component" called ISettings
public class GlobalSettings : ISettings { ... }
// elsewhere in code
public LocalizedContent GetLocalizedContent ()
{
LocalizedContent content = new LocalizedContent (GlobalSettings.Instance);
return content;
}
If you are not able to modify GlobalSettings singleton,
// wrapper class for global settings singleton
public class Settings : ISettings
{
public string CultureName
{
get { return GlobalSettings.Instance.CultureName; }
}
}
// elsewhere in code
public LocalizedContent GetLocalizedContent ()
{
LocalizedContent content = new LocalizedContent (new Settings ());
return content;
}
Now, LocalizedContent is no longer tightly-coupled to GlobalSettings singleton. In fact, any implementation of ISettings will satisfy its constructor dependency.
If your dependencies are as simple as a string or two, this may be overkill. However, if you have other complex components dependent on this global singleton, this approach may be for you :)