Calling all ISomething instances in Ninject
Asked Answered
V

2

6

I have an interface ISomething with a method Start. I want to get all implementations of this interface (in multiple assemblies, the main one and all referenced ones) and call the Start method on application start. How can I do this with Ninject 2.2.0.0 .NET 4.0?

Autofac answer was here Calling all ISomething instances in Autofac

Verticillate answered 17/3, 2011 at 23:12 Comment(0)
B
10

You may try Ninject.Extensions.Conventions :

var kernel = new StandardKernel();
kernel.Bind(c =>
            c.FromThisAssembly()
                .SelectAllClasses().InheritedFrom<IFoo>()
                .BindAllInterfaces());

// and later:

kernel.GetAll<IFoo>().ToList().ForEach(foo => foo.DoSmth());

Needed classes are below:

public interface IFoo
{
    void DoSmth();
}

public class Foo1 : IFoo
{
    public void DoSmth()
    {
        Console.Out.WriteLine("Foo1");
    }
}

public class Foo2 : IFoo
{
    public void DoSmth()
    {
        Console.Out.WriteLine("Foo2");
    }
}
Biamonte answered 26/10, 2012 at 13:19 Comment(0)
A
0

You could use reflection to find all classes that implement the interface(s): http://cocaine.co.nz/Home/High-On-Ninject-BLLModule

What do you mean by the "main one"? - call the Start() method on which one?

Amalburga answered 30/6, 2011 at 11:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.