Created
February 7, 2019 23:21
-
-
Save JimBobSquarePants/d57ac804693bd7c73de43f1edbb407ba to your computer and use it in GitHub Desktop.
A very simple demo of how to use events in DI environments.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Context
https://twitter.com/zpqrtbnk/status/1093465481686724609