Skip to content

Instantly share code, notes, and snippets.

@JimBobSquarePants
Created February 7, 2019 23:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JimBobSquarePants/d57ac804693bd7c73de43f1edbb407ba to your computer and use it in GitHub Desktop.
Save JimBobSquarePants/d57ac804693bd7c73de43f1edbb407ba to your computer and use it in GitHub Desktop.
A very simple demo of how to use events in DI environments.
// A very simple service example contract with an event.
// Using an interface ensures that every implementation has same events.
public interface IContentService
{
event EventHandler Saved;
}
// Our component contract
public interface IComponent : IDisposable
{
}
// And your custom component.
// Subscription and unsubscription are now bound to the lifecycle of the component which should be managed ultimately by the container.
public class MyComponent : IComponent
{
private readonly IContentService contentService;
public MyComponent(IContentService contentService)
{
this.contentService = contentService;
this.contentService.Saved += this.ContentServiceOnSaved;
}
public void Dispose() => this.contentService.Saved -= this.ContentServiceOnSaved;
private void ContentServiceOnSaved(object sender, EventArgs e)
{
// Do your thing.
}
}
@JimBobSquarePants
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment