如何在使用我的库的项目中添加我所有的 .net 标准库 DI 依赖项而不单独添加它们

How to add all my .net standard library DI dependencies in a project that uses my library without adding them all individually

我希望能够像 Telerik 和 sweetalert 那样做 services.AddMyCustomLibrary() 而不是像

那样必须从 MyCustomLibrary 添加每项服务
services.AddSingleton<MyCUstomLibrary.MyService>(); 

我要添加到 MyCustomLibrary 的代码是什么?

我想要这个:

    builder.Services.AddTelerikBlazor();
    builder.Services.AddSweetAlert2(options => {
        options.Theme = SweetAlertTheme.Bootstrap4;
    }); 

不是这个:

    builder.Services.AddScoped<ComponentService>();
    builder.Services.AddScoped<AppState>();

您需要为 IServiceCollection 创建带有扩展方法的静态 class。在扩展方法里面,你可以写你的库注册:

public static class Service Collection Extension {
    public static IServiceCollection AddMyCustomLibrary(this IServiceCollection services) {
       services. AddSingleton<MyCUstomLibrary.MyService>();
    } 
}

然后用法如下:

services.AddMyCustomLibrary();

编辑:您还可以创建允许您将一些属性传递给库的选项操作。

public class MyCustomLibraryOptions {
    public string MyProperty { get; set; } 
} 

public static class Service Collection Extension {
        public static IServiceCollection AddMyCustomLibrary(this IServiceCollection services, Action<MyCustomLibraryOptions> configure) {
    var options = new MyCustomLibraryOptions();
    configure?.Invoke(options);
    var myProp = options.MyProperty; //You can access options after action invocation. 
           services. AddSingleton<MyCUstomLibrary.MyService>();
        } 
    }

用法:

services.AddMyCustomLibrary(config => {
    config.MyProperty = "some value";
});