Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor/Razor Class Library. Dependency Injection

I am confused on how to use a Razor Class Library that requires injected objects. I created a new razor class library project. There is no program.cs file and hence no WebAssemblyHostBuilder to add services to? How do I inject dependencies into the components?

like image 314
Paul Stanley Avatar asked Jul 26 '26 15:07

Paul Stanley


1 Answers

A library is simply that. It's not an application. You load the DI objects in the application project. You can write extension classes in your library as a wrapper to load all the necessary objects. builder.Services.AddServerSideBlazor() is just such an extension.

Here's an example extension method for the Weather Forecast.

    public static class ServiceCollectionExtensions
    {
        public static void AddWeatherServices(this IServiceCollection services)
        {
            services.AddSingleton<WeatherForecastService>();
        }
    }

And use it in the application startup:

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

You inject the services into your components as normal. If you use a component in an application and the necessary services aren't loaded the page on which the component is being used will throw an error.

like image 160
MrC aka Shaun Curtis Avatar answered Jul 28 '26 05:07

MrC aka Shaun Curtis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!