基于类批注或继承的类型扫描程序集和自动绑定
本文关键字:程序集 绑定 扫描 类型 于类批 继承 | 更新日期: 2023-09-27 17:59:52
我需要扫描所有程序集,查找具有特定属性的类(或从抽象类ColorTest继承的类),并自动将它们绑定到ColorTestolorTest的所有实现
组件1:
public abstract class ColorTest {
public abstract string GetColorString();
}
组件2:
//[ColorImplementation] // attributes are not necessary
public class BlueColor() : ColorTest {...}
组件3:
//[ColorImplementation] //not necessary
public class RedColor() : ColorTest {...}
组件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()));
}
示例是一个抽象&简化更复杂的问题。
Ninject能帮我处理描述的场景吗?如果是,如何?
解决方案非常简单!
我不得不更换2行:
.FromAssembliesMatching("*") -> .FromAssembliesMatching(".") //mistake
和
.BindAllInterfaces() -> .BindBase() // because I'm implementing
// abstract class, not interface
属性不涉及