创建一个自定义属性(称为AutoBindAttribute)
public class AutoBindAttribute : Attribute
{
}
像下面这样使用它(装饰要与[AutroBind]自动绑定的所有实现)
public interface IMyClass {}
[AutoBind]
public class MyClass : IMyClass {}
现在为IServiceCollection创建一个扩展方法
public class ServiceCollectionExtentions
{
public static void AutoBind(this IServiceCollection source, params Assembly[] assemblies)
{
source.Scan(scan => scan.FromAssemblies(assemblies)
.AddClasses(classes => classes.WithAttribute<AutoBindAttribute>())
.AsImplementedInterfaces()
.WithTransientLifetime();
}
}
现在在Startup.cs中调用它
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AutoBind(typeof(Startup).Assembly);
}
}
注意:您可以改善 ServiceCollectionExtentions
该类以支持所有范围,例如单例等。本示例仅针对瞬态生命周期显示。
请享用!!!