Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

c# - How to wire events with methods using Autofac?

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

someType.Output += someOtherType.Input;

For example Spring.net does support the following construct to achieve that:

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

Is Autofac able to do that and how? Is it possible to use xml config for such a task?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I assume that you objects have no direct dependency together, like :

    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 either use Activated or bind a 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();

Delegate version, replace registration by:

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

As a side note, doing this type of binding can sometimes be a bit dangerous (as you create an event dependency) and create memory leak.

Creating a small class that attach both elements and implement IDisposable to unregister event when not needed anymore could be a sensible option.

I don't think it is possible to wire events via xml configuration, and for this type of binding I would largely prefer the compile time safety offered by code, but maybe you have a use case for xml.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...