简体   繁体   中英

Can delegates be registered with Castle Windsor IOC container?

This is probably a dumb question, but can delegates or events be registered with an IOC container (eg Windsor)?

I'm envisaging registering event functionality at application startup time, implementing the strategy pattern.

An alternative would be to simply wrap any delegates in types for registration with the container, I presume.

No need to wrap or subclass functions to register them in Windsor. They work just like any other component. If you need to tell one Func<int> from another, use named components and service overrides, just as with any other component. Example:

[Test]
public void Example() {
    var container = new DefaultKernel();
    container.Register(Component.For<Func<int>>().Instance(() => 42).Named("42"));
    container.Register(Component.For<Func<int>>().Instance(() => 44).Named("44"));
    container.Register(Component.For<Something>().DependsOn(ServiceOverride.ForKey("f").Eq("44")));
    var s = container.Resolve<Something>();
    Assert.AreEqual(44, s.I);
}

class Something {
    private readonly int i;
    public Something(Func<int> f) {
        i = f();
    }

    public int I {
        get { return i; }
    }
}

If you're looking to decouple your event registrations using the container, just use the Event wiring facility .

I'd say this is not possible because how would you resolve the dependancy?

If a class is asking for a delegate of type Func<bool> say, how would you distinguish between different delegates?

Your alternative of wrapping the delegate would be the best solution, as it allows you to name and combine delegates into functional sections.

EDIT Turns out Castle Windsor has a way of naming instances as they are registered in the IOC. So it is possible, but you still need to give some sort of name to each instance. See Mauricio Scheffer's answer .

As noted, it works just fine, be be careful if you are using the typed factory facility as it can present some unexpected behavior. Your delegate dependencies may spawn the creation of proxy factories. See this question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM