ASP.NET 单例中的事件处理

ASP.NET Event handling in Singleton

我正在创建 Web 应用程序,使用 ASP.NET MVC4 和 SignalR。 我尝试为某些游戏 class 创建存储库。 另外,我想在每次添加项目时触发事件。

C#

public class Repository : Dictionary<string, Game>
{
    private static Repository _instance;

    public delegate void AddItemEventHandler(object sender, EventArgs e);
    private AddItemEventHandler handler;

    public event AddItemEventHandler OnAddItem
    {
        add 
        {
            if(handler != null)
            {
                handler -= value;
            }                
            handler += value;
        }
        remove 
        {
            handler -= value;
        }
    }     

    public static Repository Instance 
    {
        get
        {
            if (_instance == null)
            {
                _instance = new Repository();
            }
            return _instance;
        }
    }

    private Repository()
    {}

    public void Add(Game model)
    {
        string key = model.Guid.ToString();
        if (!_instance.ContainsKey(key))
        {
            _instance.Add(key, model);
            if (handler != null)
            {
                handler(this, new EventArgs());
            }                
        }       
    }
}

处理程序添加到 MVC 操作中:

Repository.Instance.OnAddItem += Repository_OnAddItem;
Repository.Instance.Add(game);

处理程序在其控制器中声明:

void Repository_OnAddItem(object sender, EventArgs e)
    {
        IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<SPSHub>();
        hubContext.Clients.All.addItem();
    }

但是,每次我将项目添加到存储库时,都会添加新的相同处理程序并增加事件处理。

感谢Daniel J.G.:

"Yes, it will be a different handler because a new controller instance is created and used per request. However you can make that method a static one or move it into some other singleton object. That should fix your problem and you also won't need to add the handler every time you add an item to the repository (which seemed like an odd thing to me anyway), you would add it once in some sort of startup method."