conficient / BlazorTemplater

A library that generates HTML (e.g. for emails) from Razor Components
Apache License 2.0
146 stars 16 forks source link

Dependency Injection #22

Closed dajma00 closed 2 years ago

dajma00 commented 2 years ago

In our Blazor components, we frequently use dependency injection using the @inject or [Inject] attributes in C# code. When creating an HTML string, we get the following error in the console:

Unhandled exception rendering component: Cannot provide a value for property 'AppState' on type 'Invoice2.Client.Pages.InvoiceView'. There is no registered service of type 'Invoice2.Shared.AppState'.
System.InvalidOperationException: Cannot provide a value for property 'AppState' on type 'Invoice2.Client.Pages.InvoiceView'. There is no registered service of type 'Invoice2.Shared.AppState'.

Otherwise the component works just fine. Is there a way around this?

conficient commented 2 years ago

Did you add the service in the setup?

var appstate = new AppState(...);
var html = new ComponentRenderer<InvoiceView>()
      .AddService<AppState>(appstate)
      .Render();
conficient commented 2 years ago

I should point out that the component renderer can't plug directly into your Dependency Injection container. If you're calling it from a Controller you should inject the instance you need in the Controller's constructor so it's present when you execute the action.

conficient commented 2 years ago

Closed - no update