How to bind events to methods using Autofac?

Is it possible to associate events with Autofac methods, and not with the whole object through interfaces / classes (through the constructor and property nesting). I want to bind at the function level instead of the type level. Programmatically, I expect the following work to be done (in C #):

someType.Output += someOtherType.Input;

For example, Spring.net supports the following construction to achieve this:

<object id="SomeType" type="Whatever.SomeType, Whatever" />
<object id="SomeOtherType" type="Whatever.SomeOtherType, Whatever">
  <listener event="Output" method="Input">
    <ref object="SomeType" />
  </listener>
</object>

Can Autofac do it and how? Is it possible to use the xml configuration for such a task?

+4
source share
1 answer

I assume that your objects do not have a direct dependency, for example:

    public class SomeType
{
    public event EventHandler Input;

    public void Raise()
    {
        if (Input != null)
        {
            Input(this, new EventArgs());
        }
    }
}

public class SomeOtherType
{      
    public void Output(object source, EventArgs handler)
    {
        Console.WriteLine("Handled");
    }
}

You can use the Activate or link delegate:

Activated:

        ContainerBuilder cb = new ContainerBuilder();

        cb.RegisterType<SomeOtherType>();
        cb.RegisterType<SomeType>()
            .OnActivated(act => 
            { 
                var other = act.Context.Resolve<SomeOtherType>(); 
                act.Instance.Input += other.Output; 
            });
        var container = cb.Build();

        var obj2 = container.Resolve<SomeType>();
        obj2.Raise();

, :

        cb.Register(ctx =>
        {
            var other = ctx.Resolve<SomeOtherType>();
            var obj = new SomeType();
            obj.Input += other.Output;
            return obj;
        }).As<SomeType>();

, ( ) .

, IDisposable , , .

, xml-, , , , , xml.

+7

Source: https://habr.com/ru/post/1542287/


All Articles