Ties back to my old question here:
But I really want to intercept messages AND have an instance of the handler and be able to influence the whether the message should go to the handler at all. Basically an "around advice".
Now the most traditional way of implementing something like this is via dynamic inheritance of the target object and overriding the virtual methods. The thing that I could not tell due to lack of documentation whether, NServiceBus creates or builds up its message handler instances. If it builds up, then it can't dynamically inherit, so most AoP framework is probably out of the question, otherwise most popular DI container should do the trick.
However testing with Saga handers it seems like NServiceBus builds up rather than creates new due to the requirement for a default constructor, which points to NServiceBus manually activating the class.
Yes I realize I can use good ole' OOP to solve the same problem, but I usually prefer AoP for better (less) coupling.
If all you want to do is influence if a message should go to a handler or not, then NServiceBus provides a solution for that => DoNotContinueDispatchingCurrentMessageToHandlers()
You can create a generic handler and set it up to fire before any other handlers.
public class SomeHandler: IHandleMessages<object>, ISpecifyMessageHandlerOrdering
{
public IBus Bus {get;set;}
public void Handle(object message)
{
Bus.DoNotContinueDispatchingCurrentMessageToHandlers();
}
public void SpecifyOrder(Order order)
{
order.SpecifyFirst<SomeHandler>();
}
}
For more details see this answer
Alternatively, this can be plugged in as a mutator
class StopThePipelineMutator: IMutateIncomingTransportMessages,INeedInitialization
{
public IBus Bus { get; set; }
public void MutateIncoming(TransportMessage transportMessage)
{
Bus.DoNotContinueDispatchingCurrentMessageToHandlers();
}
public void Init()
{
Configure.Component<StopThePipelineMutator>(DependencyLifecycle.InstancePerCall);
}
}
Old post, but someone looking for a way to get AOP with NServiceBus, here's a different way of doing it:
https://github.com/MeTitus/NServiceBus/commit/278b6bf4e3daba2fbdfc5295b8718609946d653d
The other way is to user PostSharp.
Related
I´ve written a library, that is implementing a third party protocol. This protocol is following the publish-subscribe pattern (over MQTT). So basically for every message, I have a publisher method and an event, that is fired when a message of certain type arrives. Now, for my needs, I want to extend this protocol with my own messages. But also, I´ve laid down these two requirements:
Keep the basic library clean only following the protocol architecture
Extend somehow the basic library with my own messages, so in code, you can use the original messages along with my own messages in one class.
I am thinking about two options here. First is to use C# extensions methods. The big advantage I see in this option is the ability to use only one class with the standard protocol architecture and in case of need, one can add a reference to the assembly with the extensions and use the extended library with my proprietary messages. No refactoring needed. On the other hand, extensions are only static methods and don´t support events.
The second option I see is to inherit a new class and use the basic library as a base. The huge advantage of this is, that I can do everything I want in the derived class. But if one decides to use the extended library after some coding, the refactoring is needed. Here I was considering to name the inherited class with the same name as the base class, but in a different namespace, so in case of need, one can change the using statement form
using Hermes
into
using Hermes.Extended
and everything else should work. But this workaround seems to me somehow dirty.
Can anybody advise me the correct way, how to solve this task? What is the best architecture for this? Is there any other way I am not seeing?
For your reference, I am also providing a snippet from the basic class, that is dealing with one message. The extension in whatever form should do basically the same, only with my own types.
public async Task NotificationOnAsync(NotificationSwitch Payload)
{
await PublishToBroker(String.Format("hermes/feedback/sound/toggleOn"), Payload.ToJSON());
}
private EventHandler<NotificationSwitchEventArgs> _notificationTurnedOn;
private object _notificationTurnedOnLock = new object();
public event EventHandler<NotificationSwitchEventArgs> NotificationTurnedOn
{
add
{
lock (_notificationTurnedOnLock)
{
_notificationTurnedOn += value;
SubscribeTopic("hermes/feedback/sound/toggleOn");
}
}
remove
{
lock (_notificationTurnedOnLock)
{
_notificationTurnedOn -= value;
if (_notificationTurnedOn is null) UnsubscribeTopic("hermes/feedback/sound/toggleOn");
}
}
}
protected virtual void OnNotificationTurnedOn(NotificationSwitchEventArgs e)
{
_notificationTurnedOn?.Invoke(this, e);
}
Thanks.
Jiri
I have a MEF container which contains hundreds of classes. What is a good way to pass messages between different classes?
I would prefer a solution that will work with any Dependency Injection (DI) container, including Unity, Castle Windsor, etc.
Note: This is a "share your knowledge, Q&A-style" entry.
Introducing the Event Publisher
This event publisher allows any class from the MEF container to send a message to any other class in the MEF container.
This code has been battle proven over a number of years, and has proven to be particularly useful when using WPF / MVVM.
It's a one-to-many subscription, so once the message is sent out, it is received by any listener that is observing messages of that custom type.
This example is for MEF, but it is also applicable to any other Dependency Injection (DI) container such as Unity, Castle Windsor, etc. If you convert EventPublisher to a singleton, you can use it with normal C# (i.e. not using a DI container). Let me know if you want me to post the code.
This code is nothing new: there are hundreds of other implementations of event publishers in the open source community, e.g. in MVVM Light. However, this example uses such a small amount of code that it's possible to see how it works under the hood, by single stepping in the debugger.
C# Usage
Add the boiler plate code to your project (see below).
Create your custom event type. This can be a class, a struct, or even an enum, e.g.:
public enum NavigationType
{
Unknown = 0,
MyOption1,
MyOption2
}
... then, I can import the eventPublisher into any class, like so:
[ImportingConstructor]
public BrokerOrderSearchResultViewModel(
IEventPublisher<NavigationType> eventPublisher,
)
{
_eventPublisher = eventPublisher;
...
... in the constructor, I can then subscribe to events of type NavigationType:
_eventPublisher.GetEvent<NavigationType>().Subscribe(o =>
{
Console.Write(o);
});
... and anywhere else, I can push events out, which will be received in the subscription:
_eventPublisher.Publish(NavigationType.MyOption1);
C# Boiler plate code
Add the Reactive Extensions (RX) NuGet package to your project.
Create this interface:
public interface IEventPublisher
{
IObservable<TEvent> GetEvent<TEvent>();
void Publish<TEvent>(TEvent sampleEvent);
}
public interface IEventPublisher<in T>
{
IObservable<TEvent> GetEvent<TEvent>() where TEvent : T;
void Publish<TEvent>(TEvent sampleEvent) where TEvent : T;
}
... with this implementation:
// NOTE: This class must be a singleton (there should only ever
// be one copy; this happens automatically in any dependency injection
// container). This class is the central dictionary that routes events
// of any incoming type, to all listeners for that same type.
[Export(typeof (IEventPublisher))]
public class EventPublisher : IEventPublisher
{
private readonly ConcurrentDictionary<Type, object> _subjects;
public EventPublisher()
{
_subjects = new ConcurrentDictionary<Type, object>();
}
public IObservable<TEvent> GetEvent<TEvent>()
{
return (ISubject<TEvent>)_subjects.GetOrAdd(typeof(TEvent), t => new Subject<TEvent>());
}
public void Publish<TEvent>(TEvent sampleEvent)
{
object subject;
if (_subjects.TryGetValue(typeof (TEvent), out subject))
{
((ISubject<TEvent>)subject).OnNext(sampleEvent);
}
// Could add a lock here to make it thread safe, but in practice,
// the Dependency Injection container sets everything up once on
// startup and it doesn't change from that point on, so it just
// works.
}
}
// NOTE: There can be many copies of this class, one for
// each type of message. This happens automatically in any
// dependency injection container because its a <T> class.
[Export(typeof (IEventPublisher<>))]
public class EventPublisher<T> : IEventPublisher<T>
{
private readonly IEventPublisher _eventPublisher;
[ImportingConstructor]
public EventPublisher(IEventPublisher eventPublisher)
{
_eventPublisher = eventPublisher;
}
public IObservable<TEvent> GetEvent<TEvent>() where TEvent : T
{
return _eventPublisher.GetEvent<TEvent>();
}
public void Publish<TEvent>(TEvent sampleEvent) where TEvent : T
{
_eventPublisher.Publish(sampleEvent);
}
}
Discussion
This code shows how simple it is to send an event from any class to any other class.
As shown, you need to create a new custom type in order to send a message. The type can be an enum, a struct, or a class. If the type is a class or a struct, it can contain any number of properties. If a message is sent out using a specific custom type, all subscribers listening to messages of that type will receive it. You can create many custom types, one for each flavour of event you need to communicate with.
Behind the scenes, all the code is doing is keeping a dictionary of your custom types. On a send, it looks up the appropriate subscribers in the dictionary, then sends the message using Reactive Extensions (RX). All subscribers listening to that type will then receive the message.
Sometimes, if there are too many events flying everywhere, it's difficult to see which classes are communicating with which other classes. In this case, it's simple: you can use "Find in Files" to find all classes that contain the string IEventPublisher<NavigationType>, which ends up listing all of the classes that are either sending or listening to an event of our custom type NavigationType.
Beware: this code is not a silver bullet. It is a bad code smell to rely on events too much, as the class hierarchy should be composed in such a way that classes should not be dependent on their parents. For more information, study the SOLID principles, in particular, the LSP. However, sometimes use of events are unavoidable, as we have no choice but to cross the class hierarchy.
Future Enhancements
Currently, this Event Publisher does not implement IDisposable. It should.
Use EventAggregator if you're not looking to do something overly elaborate.
http://blogs.msdn.com/b/gblock/archive/2009/02/23/event-aggregation-with-mef-with-and-without-eventaggregator.aspx
And a way to bring this into your project the MEFfy way:
https://msdn.microsoft.com/en-us/library/microsoft.practices.prism.mefextensions.events.mefeventaggregator(v=pandp.50).aspx
You could also write your own EventAggregator patter (per M. Fowler), but then you would have to take into consideration cleanly removing subscribed handlers, which will most likely lead you into the land of weak references and the horrors (or not) that lie there.
I have various individual methods which all need to perform the same functions before continuing on with their own implementation. Now I could implement these functions in each method, but I was wondering if there's a way to exploit attributes to do this? As a very simple example, all network calls have to check for a network connection.
public void GetPage(string url)
{
if(IsNetworkConnected())
...
else
...
}
This would work, but I'd have to call the IsNetworkConnected method for each method that uses the network and handle it individually. Instead, I'd like to do this
[NetworkCall]
public void GetPage(string url)
{
...
}
If the network is unavailable, an error method is called instead and GetPage is ignored, otherwise GetPage is invoked.
This sounds very much like Aspect Orientated Programming, but I don't want to implement an entire framework for a few calls. This is more of a learning exercise than an implementation one, so I was curious as to how something like this would be best implemented.
You can use PostSharp, it is aspect-oriented framework for .NET, it seems quite easy to use:
static void Main(string[] args)
{
Foo();
}
[IgnoreMethod(IsIgnored=true)]
public static void Foo()
{
Console.WriteLine("Executing Foo()...");
}
[Serializable]
public class IgnoreMethodAttribute : PostSharp.Aspects.MethodInterceptionAspect
{
public bool IsIgnored { get; set; }
public override void OnInvoke(PostSharp.Aspects.MethodInterceptionArgs args)
{
if (IsIgnored)
{
return;
}
base.OnInvoke(args);
}
}
Method-Level Aspects feature is available in the free edition: http://www.sharpcrafters.com/purchase/compare
Run-Time Performance:
Because PostSharp is a compiler technology, most of the expensive work is done at build time, so that applications start quickly and execute fast. When generating code, PostSharp takes the assumption that calling a virtual method or getting a static field is an expensive operation. Contrary to rumor, PostSharp does not use System.Reflection at run time.
http://www.sharpcrafters.com/postsharp/performance
I don't think you can do this with attributes only, because they are not executed by the runtime if you're not actively doing something with them. A lightweight approach would be Ninject with Interceptions extension, it is a framework, but a very thin one, and one you might already be using for DI anyway.
Another option, but a bit more involved, could be based on MEF, and then you can use attributes and do something during with them during activation.
You're right, it sounds a lot like AOP.
What you're after sounds like compile time weaving? I.e. the attribute is turned into additional code by the compiler.
You could look at how to implement this...
Generating additional code through a custom attribute
http://www.cs.columbia.edu/~eaddy/wicca/ &
http://www.sharpcrafters.com/aop.net/compiletime-weaving
all refer to tools and techniques for doing this.
Or you could use an AOP framework. IMHO, you should look at AOP frameworks.
Is there a way in NServiceBus to replace the IHandleMessages<> handler with my own version of this interface that isnt strongly tied to NServiceBus?
I have found ways of replacing the event/command marker interfaces (Via NServiceBus 3 Unobtrusive syntax) but no way of doing the same for the actual handler. I am trying to do this to remove the coupling between my handlers and NServiceBus.
I found it possible with little code required:
1) Create a generic class implementing IHandleMessages<TMessage> and implement the Handle method making it find or create the correct instance of your custom handler (from DI container, static registry etc.). In this example assume that you've got MyCustomHandler class with void HandleMessageMyWay(object message) method accepting any message type:
public class MessageHandlerAdapter<TMessage>
: IHandleMessages<TMessage>
{
public void Handle(TMessage message)
{
new MyCustomHandler().HandleMessageMyWay(message);
}
}
It's an open generic, so NServiceBus won't discover it as a valid handler, because you need a closed generic (with TMessage being a concrete type like MyMessage1) to be seen by NServiceBus as a handler for the concrete type.
2) Implement ISpecifyMessageHandlerOrdering. In it's SpecifyOrder method make (at runtime) a closed generic adapter type for each message type which you want to support:
public class MessageHandlerAdapterLister : ISpecifyMessageHandlerOrdering
{
public void SpecifyOrder(Order order)
{
//You would normally iterate through your message types (over DI registry or some other registry of messages):
var adapterType1 = typeof(MessageHandlerAdapter<>).MakeGenericType(typeof(MyMessage1));
var adapterType2 = typeof(MessageHandlerAdapter<>).MakeGenericType(typeof(MyMessage2));
order.Specify(new[] { adapterType1, adapterType2 });
}
}
ISpecifyMessageHandlerOrdering instances are automatically discovered by NServiceBus. These are normally used to specify order for handler types which are discovered by NServiceBus. Apparently when you specify types which have not been discovered (like our closed generic adapter types made at runtime), it will simply add them to the registry.
That's all you need. NServiceBus will route MyMessage1 and MyMessage2 through the open generic IHandleMessages<TMessage> which then delegates handling to your custom class.
The reason for the NServiceBus 3.0 Unobtrusive Mode (see Andreas Ohlund's article on this) is that event definitions shared between multiple services can get into trouble if different endpoints are running different versions of NServiceBus, because the version on NServiceBus.dll that you are taking a dependency on will not match.
This argument does not hold water with the message handlers (the classes implementing IHandleMessages) themselves. There's no sharing of handlers. The message handler is, by definition, coupled to NServiceBus.
This seems to not be possible with NServiceBus.
The way i made this as unobtrusive as possible was to create a NServiceBus proxy to forward messages to my own bus, this kept the NServiceBus references out of most of my projects.
I have some debugging functions that I would like to refactor, but seeing as they are debugging functions, it seems like they would be less likely to follow proper design. They pretty much reach into the depths of the app to mess with things.
The main form of my app has a menu containing the debug functions, and I catch the events in the form code. Currently, the methods ask for a particular object in the application, if it's not null, and then mess with it. I'm trying to refactor so that I can remove the reference to this object everywhere, and use an interface for it instead (the interface is shared by many other objects which have no relation to the debugging features.)
As a simplified example, imagine I have this logic code:
public class Logic
{
public SpecificState SpecificState { get; private set; }
public IGenericState GenericState { get; private set; }
}
And this form code:
private void DebugMethod_Click(object sender, EventArgs e)
{
if (myLogic.SpecificState != null)
{
myLogic.SpecificState.MessWithStuff();
}
}
So I'm trying to get rid of the SpecificState reference. It's been eradicated from everywhere else in the app, but I can't think of how to rewrite the debug functions. Should they move their implementation into the Logic class? If so, what then? It would be a complete waste to put the many MessWithStuff methods into IGenericState as the other classes would all have empty implementations.
edit
Over the course of the application's life, many IGenericState instances come and go. It's a DFA / strategy pattern kind of thing. But only one implementation has debug functionality.
Aside: Is there another term for "debug" in this context, referring to test-only features? "Debug" usually just refers to the process of fixing things, so it's hard to search for this stuff.
Create a separate interface to hold the debug functions, such as:
public interface IDebugState
{
void ToggleDebugMode(bool enabled); // Or whatever your debug can do
}
You then have two choices, you can either inject IDebugState the same way you inject IGenericState, as in:
public class Logic
{
public IGenericState GenericState { get; private set; }
public IDebugState DebugState { get; private set; }
}
Or, if you're looking for a quicker solution, you can simply do an interface test in your debug-sensitive methods:
private void DebugMethod_Click(object sender, EventArgs e)
{
var debugState = myLogic.GenericState as IDebugState;
if (debugState != null)
debugState.ToggleDebugMode(true);
}
This conforms just fine with DI principles because you're not actually creating any dependency here, just testing to see if you already have one - and you're still relying on abstractions over concretions.
Internally, of course, you still have your SpecificState implementing both IGenericState and IDebugState, so there's only ever one instance - but that's up to your IoC container, none of your dependent classes need know about it.
I'd highly recommend reading Ninject's walkthrough of dependency injection (be sure to read through the entire tutorial). I know this may seem like a strange recommendation given your question; however, I think this will save you a lot of time in the long run and keep your code cleaner.
Your debug code seems to depend on SpecificState; therefore, I would expect that your debug menu items would ask the DI container for their dependencies, or a provider that can return the dependency or null. If you're already working on refactoring to include DI, then providing your debug menu items with the proper internal bits of your application as dependencies (via the DI container) seems to be an appropriate way to achieve that without breaking solid design principles. So, for instance:
public sealed class DebugMenuItem : ToolStripMenuItem
{
private SpecificStateProvider _prov;
public DebugMenuItem(SpecificStateProvider prov) : base("Debug Item")
{
_prov = prov;
}
// other stuff here
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
SpecificState state = _prov.GetState();
if(state != null)
state.MessWithStuff();
}
}
This assumes that an instance of SpecificState isn't always available, and needs to be accessed through a provider that may return null. By the way, this technique does have the added benefit of fewer event handlers in your form.
As an aside, I'd recommend against violating design principles for the sake of debugging, and have your debug "muck with stuff" methods interact with your internal classes the same way any other piece of code must - by its interface "contract". You'll save yourself a headache =)
I'd be inclined to look at dependency injection and decorators for relatively large apps, as FMM has suggested, but for smaller apps you could make a relatively easy extension to your existing code.
I assume that you push an instance of Logic down to the parts of your app somehow - either though static classes or fields or by passing into the constructor.
I would then extend Logic with this interface:
public interface ILogicDebugger
{
IDisposable PublishDebugger<T>(T debugger);
T GetFirstOrDefaultDebugger<T>();
IEnumerable<T> GetAllDebuggers<T>();
void CallDebuggers<T>(Action<T> call);
}
Then deep down inside your code some class that you want to debug would call this code:
var subscription =
logic.PublishDebugger(new MessWithStuffHere(/* with params */));
Now in your top-level code you can call something like this:
var debugger = logic.GetFirstOrDefaultDebugger<MessWithStuffHere>();
if (debugger != null)
{
debugger.Execute();
}
A shorter way to call methods on your debug class would be to use CallDebuggers like this:
logic.CallDebuggers<MessWithStuffHere>(x => x.Execute());
Back, deep down in your code, when your class that you're debugging is about to go out of scope, you would call this code to remove its debugger:
subscription.Dispose();
Does that work for you?