Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling all ISomething instances in Ninject

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

like image 778
Paul Avatar asked Mar 17 '11 23:03

Paul


1 Answers

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");
    }
}
like image 198
the_joric Avatar answered Oct 12 '22 18:10

the_joric