我希望能够像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创建带有扩展方法的静态类。在扩展方法内部,您可以编写您的库注册:
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";
});