简体   繁体   English

根据类注释或继承的类型扫描程序集和自动绑定

[英]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 . 我需要扫描所有程序集以查找具有特定属性的类(或从抽象类ColorTest继承的类)并将它们自动绑定到ColorTest Then I need to instantiate and enumerate all implementations of ColorTest 然后,我需要实例化并枚举ColorTest的所有实现

Assembly 1: 组装1:

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

Assembly 2: 组装2:

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

Assembly 3: 组装3:

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

Assembly 4: 组装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? Ninject可以帮我处理所描述的情况吗? If yes how? 如果是,怎么办?

Solution was pretty easy! 解决方案非常简单!

I had to replace 2 lines: 我必须替换2行:

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

and

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

Attributes were not involved 不涉及属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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