Search code examples
.netnugetblazor

How would one create a .NET Blazor service wrapped in a NuGet package?


The Blazor service lifetime is really simple, you call the Services.AddSingleton<*your any class*>();, Services.AddTransient<*your any class*>(); or Services.AddScoped<*your any class*>(); in Program.cs & you register the contents of that class to be accessible via DI in the scope of the runtime.

How would you wrap up a perhaps particularly complex set of functionality into a NuGet package and then create an instance of that in a service in Blazor that has a nice interface for instance?

Like the following:

using SomeNuGetPackage_1;
using SomeNuGetPackage_2;
using SomeNuGetPackage_3;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();

// add custom services
builder.Services.AddSingleton<NugetPackage_1_serviceClass>();
builder.Services.AddTransient<NugetPackage_2_serviceClass>();
builder.Services.AddScoped<NugetPackage_3_serviceClass>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment()) {
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

No attempt made to create the NuGet package thus far, as not really sure where to start.


Solution

  • Say you have a nuget package that contains an example 'SalesApi' class that takes two parameters in the constructor. It may look like the following:

    public interface ISalesApi {}
    
    public class SalesApi : ISalesApi
    {
        protected JObject _request;
        public SalesApi(string url, string key)
        {
            _request["url"] = "url";
            _request["userToken"] = ApiAuthenticator.GenerateToken(key);
        }
    }
    

    From your other solution that references this SalesApi nuget package you could instantiate SalesApi in Program.cs via dependency injection:

    builder.Services.AddSingleton<ISalesApi, SalesApi>(x => new SalesApi("urlValue", "apiKeyValue"));
    

    From there you access the service as you normally would:

    [Inject]
    ISalesApi Api { get; set; }
    

    This would be the most simple implementation with a class that takes parameters. You could use the Options pattern or create your own service collection. There are lots of different ways to approach this problem.