Search code examples
c#ninject-extensions

Scan assemblies and automatic binding based on class annotations or inherited type


I need to scan all assemblies for classes with specific attribute (or classes inherited from abstract class ColorTest) and automaticly bind them to ColorTest. Then I need to instantiate and enumerate all implementations of ColorTest

Assembly 1:

public abstract class ColorTest { 
    public abstract string GetColorString();
}

Assembly 2:

//[ColorImplementation] // attributes are not necessary
public class BlueColor() : ColorTest {...}

Assembly 3:

//[ColorImplementation] //not necessary
public class RedColor() : ColorTest {...}

Assembly 4:

class Program{
    public static Main(){

        #region Problem area :)
        var kernel = new StandardKernel();

        kernel.Bind(x => x
            .FromAssembliesMatching("*")
            .SelectAllClasses()
            .InheritedFrom<ColorTest>// or .WithAttribute<ObsoleteAttribute>()
            .BindAllInterfaces() // I'd like to Bind it only to ColorTest
            .Configure(b => b.InSingletonScope()));
        #endregion

        // Enumerate
        kernel
            .GetAll<ColorTest>()
            .ToList()
            .ForEach(t=>Console.WriteLine(t.GetColorString()));
}

Example is an abstraction & simplification of more complex problem.

Can Ninject serve me to handle described scenario? If yes how?


Solution

  • Solution was pretty easy!

    I had to replace 2 lines:

    .FromAssembliesMatching("*") -> .FromAssembliesMatching(".") //mistake
    

    and

    .BindAllInterfaces() -> .BindBase() // because I'm implementing 
                                        // abstract class, not interface
    

    Attributes were not involved