├── .gitattributes ├── .gitignore ├── LICENSE ├── PubSub.Tests ├── CoreHubTests.cs ├── ExtensionTests.cs ├── ExtensionWithTaskTest.cs ├── IocExtensionsTests.cs ├── PubSub.Tests.csproj └── strong-name.snk ├── PubSub.sln ├── PubSub ├── Core │ └── Hub.cs ├── Ioc │ ├── Implementation │ │ ├── PubSubPipeLineFactory.cs │ │ ├── Publisher.cs │ │ └── Subscriber.cs │ └── Interfaces │ │ ├── IPubSubPipelineFactory.cs │ │ ├── IPublisher.cs │ │ └── ISubscriber.cs ├── Properties │ └── AssemblyInfo.cs ├── PubSub.csproj └── strong-name.snk └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.sln.docstates 8 | 9 | .vs/ 10 | 11 | # Build results 12 | 13 | [Dd]ebug/ 14 | [Rr]elease/ 15 | x64/ 16 | build/ 17 | [Bb]in/ 18 | [Oo]bj/ 19 | 20 | # Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets 21 | !packages/*/build/ 22 | 23 | # MSTest test Results 24 | [Tt]est[Rr]esult*/ 25 | [Bb]uild[Ll]og.* 26 | 27 | *_i.c 28 | *_p.c 29 | *.ilk 30 | *.meta 31 | *.obj 32 | *.pch 33 | *.pdb 34 | *.pgc 35 | *.pgd 36 | *.rsp 37 | *.sbr 38 | *.tlb 39 | *.tli 40 | *.tlh 41 | *.tmp 42 | *.tmp_proj 43 | *.log 44 | *.vspscc 45 | *.vssscc 46 | .builds 47 | *.pidb 48 | *.log 49 | *.scc 50 | 51 | # Visual C++ cache files 52 | ipch/ 53 | *.aps 54 | *.ncb 55 | *.opensdf 56 | *.sdf 57 | *.cachefile 58 | 59 | # Visual Studio profiler 60 | *.psess 61 | *.vsp 62 | *.vspx 63 | 64 | # Guidance Automation Toolkit 65 | *.gpState 66 | 67 | # ReSharper is a .NET coding add-in 68 | _ReSharper*/ 69 | *.[Rr]e[Ss]harper 70 | 71 | # TeamCity is a build add-in 72 | _TeamCity* 73 | 74 | # DotCover is a Code Coverage Tool 75 | *.dotCover 76 | 77 | # NCrunch 78 | *.ncrunch* 79 | .*crunch*.local.xml 80 | 81 | # Installshield output folder 82 | [Ee]xpress/ 83 | 84 | # DocProject is a documentation generator add-in 85 | DocProject/buildhelp/ 86 | DocProject/Help/*.HxT 87 | DocProject/Help/*.HxC 88 | DocProject/Help/*.hhc 89 | DocProject/Help/*.hhk 90 | DocProject/Help/*.hhp 91 | DocProject/Help/Html2 92 | DocProject/Help/html 93 | 94 | # Click-Once directory 95 | publish/ 96 | 97 | # Publish Web Output 98 | *.Publish.xml 99 | 100 | # NuGet Packages Directory 101 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line 102 | packages/ 103 | *.lock.json 104 | *.nuget.props 105 | *.nuget.targets 106 | 107 | # Windows Azure Build Output 108 | csx 109 | *.build.csdef 110 | 111 | # Windows Store app package directory 112 | AppPackages/ 113 | 114 | # Others 115 | sql/ 116 | *.Cache 117 | ClientBin/ 118 | [Ss]tyle[Cc]op.* 119 | ~$* 120 | *~ 121 | *.dbmdl 122 | *.[Pp]ublish.xml 123 | *.pfx 124 | *.publishsettings 125 | 126 | # RIA/Silverlight projects 127 | Generated_Code/ 128 | 129 | # Backup & report files from converting an old project file to a newer 130 | # Visual Studio version. Backup files are not needed, because we have git ;-) 131 | _UpgradeReport_Files/ 132 | Backup*/ 133 | UpgradeLog*.XML 134 | UpgradeLog*.htm 135 | 136 | # SQL Server files 137 | App_Data/*.mdf 138 | App_Data/*.ldf 139 | 140 | 141 | #LightSwitch generated files 142 | GeneratedArtifacts/ 143 | _Pvt_Extensions/ 144 | ModelManifest.xml 145 | 146 | # ========================= 147 | # Windows detritus 148 | # ========================= 149 | 150 | # Windows image file caches 151 | Thumbs.db 152 | ehthumbs.db 153 | 154 | # Folder config file 155 | Desktop.ini 156 | 157 | # Recycle Bin used on file shares 158 | $RECYCLE.BIN/ 159 | 160 | # Mac desktop service store files 161 | .DS_Store 162 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /PubSub.Tests/CoreHubTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | 5 | namespace PubSub.Tests 6 | { 7 | [TestClass] 8 | public class CoreHubTests 9 | { 10 | private Hub _hub; 11 | private object _subscriber; 12 | private object _condemnedSubscriber; 13 | private object _preservedSubscriber; 14 | 15 | [TestInitialize] 16 | public void Setup() 17 | { 18 | _hub = new Hub(); 19 | _subscriber = new object(); 20 | _condemnedSubscriber = new object(); 21 | _preservedSubscriber = new object(); 22 | } 23 | 24 | [TestMethod] 25 | public void Publish_CallsAllRegisteredActions() 26 | { 27 | // arrange 28 | var callCount = 0; 29 | _hub.Subscribe(new object(), new Action(a => callCount++)); 30 | _hub.Subscribe(new object(), new Action(a => callCount++)); 31 | 32 | // act 33 | _hub.Publish(default(string)); 34 | 35 | // assert 36 | Assert.AreEqual(2, callCount); 37 | } 38 | 39 | [TestMethod] 40 | public void Publish_SpecialEvent_CaughtByBase() 41 | { 42 | // arrange 43 | var callCount = 0; 44 | _hub.Subscribe(_subscriber, a => callCount++); 45 | _hub.Subscribe(_subscriber, new Action(a => callCount++)); 46 | 47 | // act 48 | _hub.Publish(new SpecialEvent()); 49 | 50 | // assert 51 | Assert.AreEqual(2, callCount); 52 | } 53 | 54 | [TestMethod] 55 | public void Publish_BaseEvent_NotCaughtBySpecial() 56 | { 57 | // arrange 58 | var callCount = 0; 59 | _hub.Subscribe(_subscriber, new Action(a => callCount++)); 60 | _hub.Subscribe(_subscriber, new Action(a => callCount++)); 61 | 62 | // act 63 | _hub.Publish(new Event()); 64 | 65 | // assert 66 | Assert.AreEqual(1, callCount); 67 | } 68 | 69 | 70 | [TestMethod] 71 | public void Publish_CleansUpBeforeSending() 72 | { 73 | // arrange 74 | var liveSubscriber = new object(); 75 | 76 | // act 77 | _hub.Subscribe(_condemnedSubscriber, new Action(a => { })); 78 | _hub.Subscribe(liveSubscriber, new Action(a => { })); 79 | 80 | _condemnedSubscriber = null; 81 | GC.Collect(); 82 | 83 | _hub.Publish(default(string)); 84 | 85 | // assert 86 | Assert.AreEqual(1, _hub._handlers.Count); 87 | GC.KeepAlive(liveSubscriber); 88 | } 89 | 90 | [TestMethod] 91 | public void Subscribe_AddsHandlerToList() 92 | { 93 | // arrange 94 | var action = new Action(a => { }); 95 | 96 | // act 97 | _hub.Subscribe(_subscriber, action); 98 | 99 | // assert 100 | var h = _hub._handlers.First(); 101 | Assert.AreEqual(_subscriber, h.Sender.Target); 102 | Assert.AreEqual(action, h.Action); 103 | Assert.AreEqual(action.Method.GetParameters().First().ParameterType, h.Type); 104 | } 105 | 106 | [TestMethod] 107 | public void Unsubscribe_RemovesAllHandlers_OfAnyType_ForSender() 108 | { 109 | // act 110 | _hub.Subscribe(_preservedSubscriber, new Action(a => { })); 111 | _hub.Subscribe(_subscriber, new Action(a => { })); 112 | _hub.Unsubscribe(_subscriber); 113 | 114 | // assert 115 | Assert.IsTrue(_hub._handlers.Any(a => a.Sender.Target == _preservedSubscriber)); 116 | Assert.IsFalse(_hub._handlers.Any(a => a.Sender.Target == _subscriber)); 117 | } 118 | 119 | [TestMethod] 120 | public void Unsubscribe_RemovesAllHandlers_OfSpecificType_ForSender() 121 | { 122 | // arrange 123 | _hub.Subscribe(_subscriber, new Action(a => { })); 124 | _hub.Subscribe(_subscriber, new Action(a => { })); 125 | _hub.Subscribe(_preservedSubscriber, new Action(a => { })); 126 | 127 | // act 128 | _hub.Unsubscribe(_subscriber); 129 | 130 | // assert 131 | Assert.IsFalse(_hub._handlers.Any(a => a.Sender.Target == _subscriber)); 132 | } 133 | 134 | [TestMethod] 135 | public void Unsubscribe_RemovesSpecificHandler_ForSender() 136 | { 137 | var actionToDie = new Action(a => { }); 138 | _hub.Subscribe(_subscriber, actionToDie); 139 | _hub.Subscribe(_subscriber, new Action(a => { })); 140 | _hub.Subscribe(_preservedSubscriber, new Action(a => { })); 141 | 142 | // act 143 | _hub.Unsubscribe(_subscriber, actionToDie); 144 | 145 | // assert 146 | Assert.IsFalse(_hub._handlers.Any(a => a.Action.Equals(actionToDie))); 147 | } 148 | 149 | [TestMethod] 150 | public void Exists_EventDoesExist() 151 | { 152 | var action = new Action(a => { }); 153 | 154 | _hub.Subscribe(_subscriber, action); 155 | 156 | Assert.IsTrue(_hub.Exists(_subscriber, action)); 157 | } 158 | 159 | 160 | [TestMethod] 161 | public void Unsubscribe_CleanUps() 162 | { 163 | // arrange 164 | var actionToDie = new Action(a => { }); 165 | _hub.Subscribe(_subscriber, actionToDie); 166 | _hub.Subscribe(_subscriber, new Action(a => { })); 167 | _hub.Subscribe(_condemnedSubscriber, new Action(a => { })); 168 | 169 | _condemnedSubscriber = null; 170 | 171 | GC.Collect(); 172 | 173 | // act 174 | _hub.Unsubscribe(_subscriber); 175 | 176 | // assert 177 | Assert.AreEqual(0, _hub._handlers.Count); 178 | } 179 | 180 | [TestMethod] 181 | public void PubSubUnsubDirectlyToHub() 182 | { 183 | // arrange 184 | var callCount = 0; 185 | var action = new Action(a => callCount++); 186 | var myhub = new Hub(); 187 | 188 | // this lies and subscribes to the static hub instead. 189 | myhub.Subscribe(new Action(a => callCount++)); 190 | myhub.Subscribe(new Action(a => callCount++)); 191 | myhub.Subscribe(action); 192 | 193 | // act 194 | myhub.Publish(new Event()); 195 | myhub.Publish(new SpecialEvent()); 196 | myhub.Publish(); 197 | 198 | // assert 199 | Assert.AreEqual(7, callCount); 200 | 201 | // unsubscribe 202 | // this lies and unsubscribes from the static hub instead. 203 | myhub.Unsubscribe(); 204 | 205 | // act 206 | myhub.Publish(new SpecialEvent()); 207 | 208 | // assert 209 | Assert.AreEqual(9, callCount); 210 | 211 | // unsubscribe specific action 212 | myhub.Unsubscribe(action); 213 | 214 | // act 215 | myhub.Publish(new SpecialEvent()); 216 | 217 | // assert 218 | Assert.AreEqual(10, callCount); 219 | 220 | // unsubscribe to all 221 | myhub.Unsubscribe(); 222 | 223 | // act 224 | myhub.Publish(new SpecialEvent()); 225 | 226 | // assert 227 | Assert.AreEqual(10, callCount); 228 | } 229 | 230 | [TestMethod] 231 | public void Publish_NoExceptionRaisedWhenHandlerCreatesNewSubscriber() 232 | { 233 | // arrange 234 | _hub.Subscribe(new Action(a => new Stuff(_hub))); 235 | 236 | // act 237 | try 238 | { 239 | _hub.Publish(new Event()); 240 | } 241 | 242 | // assert 243 | catch (InvalidOperationException e) 244 | { 245 | Assert.Fail($"Expected no exception, but got: {e}"); 246 | } 247 | } 248 | 249 | internal class Stuff 250 | { 251 | public Stuff(Hub hub) 252 | { 253 | hub.Subscribe(new Action(a => { })); 254 | } 255 | } 256 | } 257 | 258 | 259 | 260 | public class Event 261 | { 262 | } 263 | 264 | public class SpecialEvent : Event 265 | { 266 | } 267 | } -------------------------------------------------------------------------------- /PubSub.Tests/ExtensionTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | 4 | namespace PubSub.Tests 5 | { 6 | [TestClass] 7 | public class ExtensionTests 8 | { 9 | [TestMethod] 10 | public void Exists_Static() 11 | { 12 | var hub = new Hub(); 13 | var action = new Action(a => { }); 14 | hub.Subscribe(action); 15 | 16 | // act 17 | var exists = hub.Exists(); 18 | 19 | // assert 20 | Assert.IsTrue(exists); 21 | 22 | hub.Unsubscribe(action); 23 | } 24 | 25 | [TestMethod] 26 | public void NotExists_Static() 27 | { 28 | var hub = new Hub(); 29 | var action = new Action(a => { }); 30 | hub.Subscribe(action); 31 | 32 | // act 33 | var exists = hub.Exists(); 34 | 35 | // assert 36 | Assert.IsFalse(exists); 37 | 38 | hub.Unsubscribe(action); 39 | } 40 | 41 | [TestMethod] 42 | public void PublishExtensions() 43 | { 44 | var hub = new Hub(); 45 | var callCount = 0; 46 | 47 | hub.Subscribe(new Action(a => callCount++)); 48 | hub.Subscribe(new Action(a => callCount++)); 49 | 50 | // act 51 | hub.Publish(new Event()); 52 | hub.Publish(new SpecialEvent()); 53 | hub.Publish(); 54 | 55 | // assert 56 | Assert.AreEqual(6, callCount); 57 | } 58 | 59 | [TestMethod] 60 | public void UnsubscribeExtensions() 61 | { 62 | var hub = new Hub(); 63 | var callCount = 0; 64 | var action = new Action(a => callCount++); 65 | 66 | hub.Subscribe(new Action(a => callCount++)); 67 | hub.Subscribe(new Action(a => callCount++)); 68 | hub.Subscribe(action); 69 | 70 | // act 71 | hub.Publish(new Event()); 72 | hub.Publish(new SpecialEvent()); 73 | hub.Publish(); 74 | 75 | // assert 76 | Assert.AreEqual(7, callCount); 77 | 78 | // unsubscribe 79 | hub.Unsubscribe(); 80 | 81 | // act 82 | hub.Publish(); 83 | 84 | // assert 85 | Assert.AreEqual(9, callCount); 86 | 87 | // unsubscribe specific action 88 | hub.Unsubscribe(action); 89 | 90 | // act 91 | hub.Publish(); 92 | 93 | // assert 94 | Assert.AreEqual(10, callCount); 95 | 96 | // unsubscribe from all 97 | hub.Unsubscribe(); 98 | 99 | // act 100 | hub.Publish(); 101 | 102 | // assert 103 | Assert.AreEqual(10, callCount); 104 | } 105 | } 106 | } -------------------------------------------------------------------------------- /PubSub.Tests/ExtensionWithTaskTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Microsoft.VisualStudio.TestTools.UnitTesting; 5 | 6 | namespace PubSub.Tests 7 | { 8 | [TestClass] 9 | public class ExtensionWithTaskTest 10 | { 11 | [TestMethod] 12 | public void Subscribe_With_Action_And_Func_Publish_All() 13 | { 14 | var hub = new Hub(); 15 | var callCount = 0; 16 | 17 | hub.Subscribe(new Action(a => callCount++)); 18 | hub.Subscribe(new Func(e => 19 | { 20 | return Task.Run(() => 21 | { 22 | Thread.Sleep(200); 23 | return callCount++; 24 | }); 25 | })); 26 | 27 | // act 28 | hub.Publish(new Event()); 29 | hub.Publish(new SpecialEvent()); 30 | hub.Publish(); 31 | 32 | // assert 33 | Assert.AreEqual(3, callCount); 34 | } 35 | 36 | [TestMethod] 37 | public void Subscribe_With_Action_And_Func_Publish_One_As_Async() 38 | { 39 | var hub = new Hub(); 40 | var callCount = 0; 41 | 42 | hub.Subscribe(new Action(a => callCount++)); 43 | hub.Subscribe(new Func(e => 44 | { 45 | return Task.Run(() => 46 | { 47 | Thread.Sleep(200); 48 | return callCount++; 49 | }); 50 | })); 51 | 52 | // act 53 | hub.PublishAsync(new Event()).Wait(); 54 | hub.Publish(new SpecialEvent()); 55 | hub.Publish(); 56 | 57 | // assert 58 | Assert.AreEqual(4, callCount); 59 | } 60 | 61 | [TestMethod] 62 | public void Subscribe_With_Action_And_Func_Publish_All_As_Async() 63 | { 64 | var hub = new Hub(); 65 | var callCount = 0; 66 | 67 | var action = new Action(a => callCount++); 68 | var func = new Func(e => 69 | { 70 | return Task.Run(() => 71 | { 72 | Thread.Sleep(200); 73 | return callCount++; 74 | }); 75 | }); 76 | 77 | // act 78 | hub.Subscribe(action); 79 | hub.Subscribe(func); 80 | 81 | hub.PublishAsync(new Event()).Wait(); 82 | hub.PublishAsync(new SpecialEvent()).Wait(); 83 | hub.PublishAsync().Wait(); 84 | 85 | // assert 86 | Assert.AreEqual(6, callCount); 87 | 88 | //act 2 89 | hub.Unsubscribe(action); 90 | hub.Unsubscribe(func); 91 | 92 | hub.PublishAsync(new Event()).Wait(); 93 | hub.PublishAsync(new SpecialEvent()).Wait(); 94 | hub.PublishAsync().Wait(); 95 | 96 | // assert 2 97 | Assert.AreEqual(6, callCount); 98 | 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /PubSub.Tests/IocExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | 4 | namespace PubSub.Tests 5 | { 6 | [TestClass] 7 | public class IocExtensionsTests 8 | { 9 | private IPubSubPipelineFactory pubSubFactory; 10 | private ISubscriber subscriber; 11 | private IPublisher publisher; 12 | private object sender; 13 | private object preservedSender; 14 | 15 | [TestInitialize] 16 | public void Setup() 17 | { 18 | pubSubFactory = new PubSubPipelineFactory(); 19 | subscriber = pubSubFactory.GetSubscriber(); 20 | publisher = pubSubFactory.GetPublisher(); 21 | sender = new object(); 22 | preservedSender = new object(); 23 | } 24 | 25 | [TestMethod] 26 | public void Publish_Over_Interface_Calls_All_Subscribers() 27 | { 28 | var callCount = 0; 29 | subscriber.Subscribe(sender, a => callCount++); 30 | subscriber.Subscribe(sender, new Action(a => callCount++)); 31 | 32 | publisher.Publish(new SpecialEvent()); 33 | 34 | Assert.AreEqual(2, callCount); 35 | } 36 | 37 | [TestMethod] 38 | public void Unsubscribe_OverInterface_RemovesAllHandlers_OfAnyType_ForSender() 39 | { 40 | subscriber.Subscribe(preservedSender, new Action(a => { })); 41 | subscriber.Subscribe(sender, new Action(a => { })); 42 | subscriber.Unsubscribe(sender); 43 | 44 | Assert.IsFalse(subscriber.Exists(sender)); 45 | Assert.IsTrue(subscriber.Exists(preservedSender)); 46 | } 47 | 48 | [TestMethod] 49 | public void Unsubscribe_OverInterface_RemovesAllHandlers_OfSpecificType_ForSender() 50 | { 51 | subscriber.Subscribe(sender, new Action(a => { })); 52 | subscriber.Subscribe(sender, new Action(a => { })); 53 | subscriber.Subscribe(preservedSender, new Action(a => { })); 54 | 55 | subscriber.Unsubscribe(sender); 56 | 57 | Assert.IsFalse(subscriber.Exists(sender)); 58 | } 59 | 60 | [TestMethod] 61 | public void Unsubscribe_RemovesSpecificHandler_ForSender() 62 | { 63 | var actionToDie = new Action(a => { }); 64 | subscriber.Subscribe(sender, actionToDie); 65 | subscriber.Subscribe(sender, new Action(a => { })); 66 | subscriber.Subscribe(preservedSender, new Action(a => { })); 67 | 68 | subscriber.Unsubscribe(sender, actionToDie); 69 | 70 | Assert.IsFalse(subscriber.Exists(sender, actionToDie)); 71 | } 72 | 73 | } 74 | } -------------------------------------------------------------------------------- /PubSub.Tests/PubSub.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Library 5 | net46 6 | true 7 | strong-name.snk 8 | 9 | 10 | true 11 | full 12 | false 13 | bin\Debug\ 14 | DEBUG;TRACE 15 | prompt 16 | 4 17 | 18 | 19 | pdbonly 20 | true 21 | bin\Release\ 22 | TRACE 23 | prompt 24 | 4 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 55 | -------------------------------------------------------------------------------- /PubSub.Tests/strong-name.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/upta/pubsub/37b327af7b0d71d7d0edb8f23be74e27ddf400f7/PubSub.Tests/strong-name.snk -------------------------------------------------------------------------------- /PubSub.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.23107.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PubSub", "PubSub\PubSub.csproj", "{C73D1486-C5C4-4BF0-AE0B-D0A214E2CCB9}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PubSub.Tests", "PubSub.Tests\PubSub.Tests.csproj", "{DC01D868-1B0E-4754-B070-F3CC4DAA7F7B}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {C73D1486-C5C4-4BF0-AE0B-D0A214E2CCB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {C73D1486-C5C4-4BF0-AE0B-D0A214E2CCB9}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {C73D1486-C5C4-4BF0-AE0B-D0A214E2CCB9}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {C73D1486-C5C4-4BF0-AE0B-D0A214E2CCB9}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {DC01D868-1B0E-4754-B070-F3CC4DAA7F7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {DC01D868-1B0E-4754-B070-F3CC4DAA7F7B}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {DC01D868-1B0E-4754-B070-F3CC4DAA7F7B}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {DC01D868-1B0E-4754-B070-F3CC4DAA7F7B}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /PubSub/Core/Hub.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Threading.Tasks; 6 | 7 | namespace PubSub 8 | { 9 | public class Hub 10 | { 11 | internal List _handlers = new List(); 12 | internal object _locker = new object(); 13 | private static Hub _default; 14 | 15 | public static Hub Default => _default ?? (_default = new Hub()); 16 | 17 | public void Publish(T data = default(T)) 18 | { 19 | foreach (var handler in GetAliveHandlers()) 20 | { 21 | switch (handler.Action) 22 | { 23 | case Action action: 24 | action(data); 25 | break; 26 | case Func func: 27 | func(data); 28 | break; 29 | } 30 | } 31 | } 32 | 33 | public async Task PublishAsync(T data = default(T)) 34 | { 35 | foreach (var handler in GetAliveHandlers()) 36 | { 37 | switch (handler.Action) 38 | { 39 | case Action action: 40 | action(data); 41 | break; 42 | case Func func: 43 | await func(data); 44 | break; 45 | } 46 | } 47 | } 48 | 49 | /// 50 | /// Allow subscribing directly to this Hub. 51 | /// 52 | /// 53 | /// 54 | public void Subscribe(Action handler) 55 | { 56 | Subscribe(this, handler); 57 | } 58 | 59 | public void Subscribe(object subscriber, Action handler) 60 | { 61 | SubscribeDelegate(subscriber, handler); 62 | } 63 | 64 | public void Subscribe(Func handler) 65 | { 66 | Subscribe(this, handler); 67 | } 68 | 69 | public void Subscribe(object subscriber, Func handler) 70 | { 71 | SubscribeDelegate(subscriber, handler); 72 | } 73 | 74 | /// 75 | /// Allow unsubscribing directly to this Hub. 76 | /// 77 | public void Unsubscribe() 78 | { 79 | Unsubscribe(this); 80 | } 81 | 82 | public void Unsubscribe(Delegate handler) 83 | { 84 | Unsubscribe(this, handler); 85 | } 86 | 87 | public void Unsubscribe(object subscriber, Delegate handler = null) 88 | { 89 | lock (_locker) 90 | { 91 | var query = _handlers.Where(a => !a.Sender.IsAlive || 92 | a.Sender.Target.Equals(subscriber)); 93 | 94 | if (handler != null) 95 | query = query.Where(a => a.Action.Equals(handler)); 96 | 97 | foreach (var h in query.ToList()) 98 | _handlers.Remove(h); 99 | } 100 | } 101 | 102 | /// 103 | /// Allow unsubscribing directly to this Hub. 104 | /// 105 | /// 106 | public void Unsubscribe() 107 | { 108 | Unsubscribe(this); 109 | } 110 | 111 | /// 112 | /// Allow unsubscribing directly to this Hub. 113 | /// 114 | /// 115 | /// 116 | public void Unsubscribe(Delegate handler) 117 | { 118 | Unsubscribe(this, handler); 119 | } 120 | 121 | public void Unsubscribe(object subscriber, Delegate handler = null) 122 | { 123 | lock (_locker) 124 | { 125 | var query = _handlers.Where(a => !a.Sender.IsAlive || 126 | a.Sender.Target.Equals(subscriber) && a.Type == typeof(T)); 127 | 128 | if (handler != null) 129 | query = query.Where(a => a.Action.Equals(handler)); 130 | 131 | foreach (var h in query.ToList()) 132 | _handlers.Remove(h); 133 | } 134 | } 135 | 136 | public bool Exists() 137 | { 138 | return Exists(this); 139 | } 140 | 141 | public bool Exists(object subscriber) 142 | { 143 | lock (_locker) 144 | { 145 | foreach (var h in _handlers) 146 | { 147 | if (Equals(h.Sender.Target, subscriber) && 148 | typeof(T) == h.Type) 149 | { 150 | return true; 151 | } 152 | } 153 | } 154 | 155 | return false; 156 | } 157 | 158 | public bool Exists(object subscriber, Action handler) 159 | { 160 | lock (_locker) 161 | { 162 | foreach (var h in _handlers) 163 | { 164 | if (Equals(h.Sender.Target, subscriber) && 165 | typeof(T) == h.Type && 166 | h.Action.Equals(handler)) 167 | { 168 | return true; 169 | } 170 | } 171 | } 172 | 173 | return false; 174 | } 175 | 176 | private void SubscribeDelegate(object subscriber, Delegate handler) 177 | { 178 | var item = new Handler 179 | { 180 | Action = handler, 181 | Sender = new WeakReference(subscriber), 182 | Type = typeof(T) 183 | }; 184 | 185 | lock (_locker) 186 | { 187 | _handlers.Add(item); 188 | } 189 | } 190 | 191 | private List GetAliveHandlers() 192 | { 193 | PruneHandlers(); 194 | return _handlers.Where(h => h.Type.GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo())).ToList(); 195 | } 196 | 197 | private void PruneHandlers() 198 | { 199 | lock (_locker) 200 | { 201 | for (int i = _handlers.Count - 1; i >= 0; --i) 202 | { 203 | if (!_handlers[i].Sender.IsAlive) 204 | _handlers.RemoveAt(i); 205 | } 206 | } 207 | } 208 | 209 | internal class Handler 210 | { 211 | public Delegate Action { get; set; } 212 | public WeakReference Sender { get; set; } 213 | public Type Type { get; set; } 214 | } 215 | } 216 | } -------------------------------------------------------------------------------- /PubSub/Ioc/Implementation/PubSubPipeLineFactory.cs: -------------------------------------------------------------------------------- 1 | namespace PubSub 2 | { 3 | public class PubSubPipelineFactory : IPubSubPipelineFactory 4 | { 5 | private readonly Hub hub; 6 | 7 | public PubSubPipelineFactory() 8 | { 9 | hub = new Hub(); 10 | } 11 | 12 | public IPublisher GetPublisher() => new Publisher( hub ); 13 | 14 | public ISubscriber GetSubscriber() => new Subscriber( hub ); 15 | } 16 | } -------------------------------------------------------------------------------- /PubSub/Ioc/Implementation/Publisher.cs: -------------------------------------------------------------------------------- 1 | namespace PubSub 2 | { 3 | public class Publisher : IPublisher 4 | { 5 | private readonly Hub hub; 6 | 7 | public Publisher( Hub hub ) 8 | { 9 | this.hub = hub; 10 | } 11 | 12 | public void Publish(T data) => hub.Publish(data); 13 | } 14 | } -------------------------------------------------------------------------------- /PubSub/Ioc/Implementation/Subscriber.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace PubSub 4 | { 5 | public class Subscriber : ISubscriber 6 | { 7 | private readonly Hub hub; 8 | 9 | public Subscriber( Hub hub ) 10 | { 11 | this.hub = hub; 12 | } 13 | 14 | public bool Exists( object subscriber ) => hub.Exists( subscriber ); 15 | 16 | public bool Exists( object subscriber, Action handler ) => hub.Exists( subscriber, handler ); 17 | 18 | public void Subscribe( object subscriber, Action handler ) => hub.Subscribe( subscriber, handler ); 19 | 20 | public void Unsubscribe( object subscriber ) => hub.Unsubscribe( subscriber ); 21 | 22 | public void Unsubscribe( object subscriber ) => hub.Unsubscribe( subscriber, (Action) null ); 23 | 24 | public void Unsubscribe( object subscriber, Action handler ) => hub.Unsubscribe( subscriber, handler ); 25 | } 26 | } -------------------------------------------------------------------------------- /PubSub/Ioc/Interfaces/IPubSubPipelineFactory.cs: -------------------------------------------------------------------------------- 1 | namespace PubSub 2 | { 3 | public interface IPubSubPipelineFactory 4 | { 5 | IPublisher GetPublisher(); 6 | ISubscriber GetSubscriber(); 7 | } 8 | } -------------------------------------------------------------------------------- /PubSub/Ioc/Interfaces/IPublisher.cs: -------------------------------------------------------------------------------- 1 | namespace PubSub 2 | { 3 | public interface IPublisher 4 | { 5 | void Publish(T data); 6 | } 7 | } -------------------------------------------------------------------------------- /PubSub/Ioc/Interfaces/ISubscriber.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace PubSub 4 | { 5 | public interface ISubscriber 6 | { 7 | bool Exists( object subscriber ); 8 | bool Exists( object subscriber, Action handler ); 9 | void Subscribe( object subscriber, Action handler ); 10 | void Unsubscribe( object subscriber ); 11 | void Unsubscribe( object subscriber ); 12 | void Unsubscribe( object subscriber, Action handler ); 13 | } 14 | } -------------------------------------------------------------------------------- /PubSub/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Resources; 2 | using System.Reflection; 3 | using System.Runtime.CompilerServices; 4 | using System.Runtime.InteropServices; 5 | 6 | // General Information about an assembly is controlled through the following 7 | // set of attributes. Change these attribute values to modify the information 8 | // associated with an assembly. 9 | //[assembly: AssemblyTitle("PubSub")] 10 | //[assembly: AssemblyDescription("")] 11 | //[assembly: AssemblyConfiguration("")] 12 | //[assembly: AssemblyCompany("")] 13 | //[assembly: AssemblyProduct("PubSub")] 14 | [assembly: AssemblyCopyright("Copyright © 2014")] 15 | [assembly: AssemblyTrademark("")] 16 | [assembly: AssemblyCulture("")] 17 | [assembly: NeutralResourcesLanguage("en")] 18 | 19 | 20 | 21 | [assembly: InternalsVisibleTo("PubSub.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010011c3aaadd5c2fb9f4719bca18995c6ea3eac95265c73d9ca2dbf89e210c92f1371e1330fa8733f33c2c788c4ce88a078a3e3e8b0fa02de3af90949f1a06ffa455ec9a1db2d6f89855041cc5508cd9652a56b83c1131b17c95bf4d5ed14bb06af48adc0917efa219902abd1247e772398b3cd304c1ec416a247101fd838d702dc")] -------------------------------------------------------------------------------- /PubSub/PubSub.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {C73D1486-C5C4-4BF0-AE0B-D0A214E2CCB9} 7 | Library 8 | netstandard1.1;netstandard2.0 9 | 15.0 10 | 11 | 12 | 12.0 13 | 14 | PubSub 15 | PubSub dotnet 16 | upta 17 | http://github.com/upta/pubsub 18 | false 19 | portable;pubsub;eventaggregator;c# 20 | An extremely light-weight, easy to use .Net pub/sub library 21 | 4.0.2 22 | True 23 | true 24 | strong-name.snk 25 | false 26 | 4.0.2.0 27 | 4.0.2.0 28 | 29 | 30 | 31 | true 32 | full 33 | false 34 | bin\Debug\ 35 | DEBUG;TRACE 36 | prompt 37 | 4 38 | 39 | 40 | pdbonly 41 | true 42 | bin\Release\ 43 | TRACE 44 | prompt 45 | 4 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 61 | -------------------------------------------------------------------------------- /PubSub/strong-name.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/upta/pubsub/37b327af7b0d71d7d0edb8f23be74e27ddf400f7/PubSub/strong-name.snk -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PubSub .Net [![Build status](https://ci.appveyor.com/api/projects/status/q228h98xg9905ghc)](https://ci.appveyor.com/project/upta/pubsub) 2 | 3 | An extremely light-weight, easy to use .Net pub/sub library 4 | 5 | ### Breaking change in 4.0 6 | In an effort to clean up some old bad habits, version 4.0 and beyond no longer has extension methods on object for Publish and Subscribe. The easiest migration solution would be to simply use those methods on the new Hub.Default static instance. 7 | 8 | ### The idea 9 | * Provide the ability to do de-coupled communication without having to include some large (and often opinionated) framework when all you want is pubsub 10 | * It should be portable so it can be used pretty much wherever 11 | * Make it stupid simple to use with zero setup 12 | 13 | ### When is it useful? 14 | In general, the publish/subscribe pattern is great when you want to communicate between pieces of your app without having those pieces being tightly dependent on each other. You might find [this article on the subject](http://blog.mgechev.com/2013/04/24/why-to-use-publishsubscribe-in-javascript/) interesting (it talks specifically about javascript, but the concept applies) 15 | 16 | A few cases where I have found this library useful (namely in mobile development): 17 | * Persisting user settings to disk asynchronously 18 | * Posting a message (i.e. Twitter) and using Subscribe to refresh lists, update counts, etc. 19 | * Providing a nice, de-coupled communication medium between Activities and their child Fragments in a Xamarin.Android application. 20 | 21 | There are lots of good applications for the publish/subscribe patterns. Have a good one I didn't think of? [Let me know](https://github.com/upta/pubsub/issues) 22 | 23 | ### How to use it 24 | First, add a using. 25 | ```c# 26 | using PubSub; 27 | ``` 28 | 29 | Listen for stuff you might be interested in. 30 | 31 | ```c# 32 | public class Page 33 | { 34 | Hub hub = Hub.Default; 35 | 36 | public Page() 37 | { 38 | hub.Subscribe(this, product => 39 | { 40 | // highly interesting things 41 | }); 42 | } 43 | } 44 | ``` 45 | 46 | Tell others that interesting things happened. 47 | 48 | ```c# 49 | public class OtherPage 50 | { 51 | Hub hub = Hub.Default; 52 | 53 | public void ProductPurchased() 54 | { 55 | hub.Publish( new Product() ); 56 | } 57 | } 58 | ``` 59 | 60 | Stop listening when you don't care anymore. 61 | 62 | ```c# 63 | public class Page 64 | { 65 | Hub hub = Hub.Default; 66 | 67 | public void WereDoneHere() 68 | { 69 | hub.Unsubscribe(); 70 | } 71 | } 72 | ``` 73 | 74 | ### Some explanation 75 | To keep things simple, yet flexible, PubSub PCL is implemented using core ideas: 76 | * Different kinds of messages are delineated by CLR type. 77 | - This avoids the need to have a list of string constants (or just magic strings), enums, whatever to define what you want to listen for/send. 78 | - This gives us nice strongly-typed data that can be passed from our Publish methods to our Subscribe handlers (i.e. Product above) 79 | 80 | ### Get it on Nuget 81 | 82 | Install-Package PubSub 83 | 84 | ![nuget dialog image for PubSub PCL](http://i.imgur.com/jH6ONPg.png "Nuget dialog for PubSub PCL") 85 | 86 | ### Target Frameworks 87 | * .Net Standard 1.1 / 2.0 88 | 89 | ### Currently supported platforms 90 | * .Net Framwork 4.5 / 4.5.1 91 | * Windows 8 / 8.1 92 | * Windows Phone Silverlight 8 / 8.1 93 | * Windows Phone 8.1 (WinRT) 94 | * Silverlight 5 95 | * Xamarin.Android 96 | * Xamarin.iOS 97 | 98 | ### Questions? Thoughts? 99 | Feel free to post stuff to the [issues](https://github.com/upta/pubsub/issues) page or hit me up on Twitter [@brianupta](https://twitter.com/brianupta) 100 | 101 | --------------------------------------------------------------------------------