Home > Enterprise >  How to add all my .net standard library DI dependencies in a project that uses my library without ad
How to add all my .net standard library DI dependencies in a project that uses my library without ad

Time:03-12

I want to be able to do services.AddMyCustomLibrary() like Telerik and sweetalert do rather than having to add every service from MyCustomLibrary like

services.AddSingleton<MyCUstomLibrary.MyService>(); 

What is the code I would add to MyCustomLibrary to make this work?

I want this:

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

Not this:

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

CodePudding user response:

You need to create static class with extension method for IServiceCollection. Inside of extension method, you can write your library registrations:

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

Then usage looks like this:

services.AddMyCustomLibrary();

Edit: you can create also options action that allows you pass some properties to your libraries.

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>();
        } 
    }

Usage:

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