我希望能夠services.AddMyCustomLibrary()像 Telerik 和 sweetalert 那樣做,而不是像添加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>();
uj5u.com熱心網友回復:
您需要為 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";
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/442180.html
