对不起标题,我会尽力解释这个问题。 我已经为我的log4net实例创建了一个包装器,我用以下构造函数实例化了这个logger:
public MyLogger(string _dbName)
{
dbName = _dbName;
logger = LoggerConfigurator.AddNamedLogger(dbName);
}
现在问题是:这个构造函数在两个不同的类中实例化,因此一些消息日志被打印两次。
我只需要在前一个实例不存在的情况下创建一个新实例,否则返回实例。一种单身人士模式。问题是Singleton模式不接受参数,所以我无法通过_dbName
。如何按照最佳实践处理此问题?
答案 0 :(得分:3)
如果我理解正确,您正在寻找一个Multiton(Multiton pattern on Wikipedia)。它基本上是每个键的单例(这是维基百科上的C#示例):
using System.Collections.Generic;
using System.Collections.Concurrent;
namespace MyApplication
{
class FooMultiton
{
private static readonly ConcurrentDictionary<object, FooMultiton> _instances
= new ConcurrentDictionary<object, FooMultiton>();
private FooMultiton() {}
public static FooMultiton GetInstance(object key)
{
_instances.TryAdd(key, new FooMultiton()); // This would of course be new MyLogger(_dbName)
return _instances[key];
}
}
}
答案 1 :(得分:1)
由于不建议给单身人士&#34; getHandle&#34;方法一个参数,我说你需要将dbName
作为单独的静态属性传递,例如
class MyLogger {
private String dbname = String.Empty;
public static String DbName {
get { return dbname; }
set { dbname = value; }
}
private static MyLogger mylogger = null;
public static MyLogger Handle {
get {
if (logger == null) mylogger = new MyLogger(dbName);
return mylogger;
}
}
private MyLogger(String db) {
// your code
logger = LoggerConfigurator.AddNamedLogger(db);
}
答案 2 :(得分:0)
class MySingleton
{
private static MySingleton _instance;
private MySingleton()
{
}
private MySingleton(params object[] parameters)
{
// assign parameters
}
public static MySingleton Instance
{
get
{
if (_instance == null)
{
throw new Exception("not created");
}
return _instance;
}
}
public static void Create(params object[] parameters)
{
if (_instance != null)
{
return;
}
_instance = new MySingleton(parameters);
}
}
需要多个线程的同步。