I am writing a service in .NET/C# that recieves updates on items. When an item is updated, i want to do several actions, and more actions will come in the future. I want to decaouple the actions from the event through some commen pattern. My brain says IOC, but I am having a hard time finding what i seek. Basically what I am thinking is having the controller that recieves the updated item, go through come config for actions that subscribes to the event and call them all. Surely there exists some lightweight, fast and easy to use framework for this, thats still up-to-date. What would you recommend and why? (emphasis on easy to use and fast).
3 Answers
There is one pattern that uses DI-container (IoC, yes). There is a lot of DI-containers and I personally use Castle Windsor. But any container should do this trick. For example, you can create such an interface:
public ISomeAction
{
void Execute(SomeArg arg);
}
And, when you need to call all the actions, you can use it like this:
var actions = container.ResolveAll<ISomeAction>();
foreach (var action in actions)
{
action.Execute(arg);
}
To "register" an action, you need to do something like this:
container.Register(Component.For<ISomeAction>().ImplementedBy<ConcreteAction());
You can use XML for this, if you want. It's very flexible solution - you can use it in any part of your app. You can implement this "for future", even if you don't need to subscribe anything. If someone would add a lib to your project, he will be able to subscribe to your event by simply registering his implementation.

- 470
- 2
- 10
-
Thanks for the answer. So do i just call the line "container.Register(Component.For
().ImplementedBy – Troels Sep 14 '17 at 13:00 -
It's one of the options. You can also register every ISomeAction implementation in lib by calling this: container.Register(Classes.FromThisAssembly().BasedOn
());, more at https://github.com/castleproject/Windsor/blob/master/docs/registering-components-by-conventions.md – Danil Eroshenko Sep 14 '17 at 13:07
If you want to use .NET events, than Castle Windsor has an interesting facility:
https://github.com/castleproject/Windsor/blob/master/docs/event-wiring-facility.md

- 4,282
- 4
- 22
- 40
In case anyone needs it, heres is how to do it in StructureMap:
var container = new Container(_ =>
{
_.Scan(x =>
{
x.TheCallingAssembly();
x.WithDefaultConventions();
x.AddAllTypesOf<IUpdateAction>();
});
});
var actions = container.GetAllInstances<IUpdateAction>();
foreach (IUpdateAction action in actions)
{
action.Execute(updatedItem);
}

- 151
- 4