Paul Stanley
Paul Stanley

Reputation: 2161

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?

Upvotes: 3

Views: 2176

Answers (2)

neds
neds

Reputation: 1

Assuming you have your services in the razor class library and your blazor app project has a project reference to your razor class library. You add the services to the app Program.cs and then in the razor class library, you just inject it where you need it.

@code{

    [Inject]
    public MyServiceType MyService {get;set}
}

Upvotes: 0

MrC aka Shaun Curtis
MrC aka Shaun Curtis

Reputation: 30001

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.

Upvotes: 5

Related Questions