I'm creating web application, using ASP.NET MVC4 and SignalR. I've tried to create repository for some Game class. Also, I want to fire event everytime item is added.
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());
}
}
}
}
The handler is added in the MVC action:
Repository.Instance.OnAddItem += Repository_OnAddItem;
Repository.Instance.Add(game);
And the handler is declared in its controller:
void Repository_OnAddItem(object sender, EventArgs e)
{
IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<SPSHub>();
hubContext.Clients.All.addItem();
}
However, every time when I add item to the repository, new identical handler is added and multiplies event handling.