I started using Autofac in my project. It's simple chat app. I have Messaging
class which belong to Node
class. Each Node
object has own instance of Messaging
. Messaging
contain several events for signalling incoming messages etc. Currently my code looks like this:
Network.cs (In library)
var scope = container.BeginLifetimeScope(b => { b.RegisterInstance(host).As<IHost>(); });
var node = scope.Resolve<Node>();
NodeCreated?.Invoke(this, node);
Program.cs (In client assembly)
Network.NodeCreated += (sender, node) => { _ = new NodeEventsHandlers(node); };
NodeEventsHandlers.cs (In client assembly)
public NodeEventsHandlers(INode node)
{
this.node = node;
node.Messaging.MessageReceived += OnMessageReceived;
...
It's mess and didn't take advantage of DI. How can I inject event handlers methods into Messaging
with Autofac? I found this but I'm not sure is it useful in my case.
There's really not enough here to guarantee a complete answer. For example, you mention you have a Messaging
class but you never show it, and that's kind of what the whole question revolves around. However, I may be able to shortcut this a bit.
Dependency injection is for constructing objects... which sounds like I'm stating the obvious, but it's an important point here because, if I'm reading the question right, you're asking how to make dependency injection wire up event handlers. That's not what DI is for, and, more specifically, that's not really something Autofac - as a dependency injection framework - would be able to help you with.
For a really, really high level concept of what Autofac can help with, think:
new
instead, Autofac can help. That is, invoking a constructor and passing parameters.Activator.CreateInstance
(the reflection way of invoking the constructor), Autofac can help.However, there's no facility in Autofac (or any other DI framework I'm aware of) that will "automatically" execute some sort of event wire-up. That's code you'd have to write yourself.
I could possibly see something where you use the Autofac OnActivating
event to call some code you write that does the event wire-up when the object is resolved, but that's about as good as it gets.
If I had to guess, I'd say you're likely looking for something closer to a service bus, where you register nodes with the pub/sub framework and that handles attaching and detaching listeners to events. That's a different type of thing entirely than Autofac.