I have a blazor component in my application:
public class IndexComponent : ComponentBase
{
public string ContentRoot { get; set; }
public string WebRoot { get; set; }
private IHostingEnvironment HostingEnvironment;
public IndexComponent(IHostingEnvironment hostingEnvironment)
{
HostingEnvironment = hostingEnvironment;
}
protected override async Task OnInitAsync()
{
//Some Code Here
}
}
I am trying to use DI in my app , for example IHostingEnvironment.
Code give no compile time error here but when i run it than in code behind file of this razor (Index.razor.g.cs file):
public class Index : IndexComponent
at this line it says:
There is no argument given that corresponds to the required formal parameter hostingEnvironment of IndexComponent.IndexComponent
This can be solved by using @inject IHostingEnvironment in Razor file but I am moving my function block from Razor to IndexComponent.cs file so need it there.
Neither of it works in below way:
[Inject]
IHostingEnvironment HostingEnvironment
What will work here?
Note: No use of ViewModel
Update 1
In StartUp.cs by adding namespace
using Microsoft.AspNetCore.Hosting.Internal;
And than
services.AddSingleton<IHostingEnvironment>(new HostingEnvironment());
It is now able to register IHostingEnvironment on client side project but it does not have values for its properties (contentrootpath and webrootpath).
Only one thing is available here which is EnvironmentName and its value is always Production ,
Access to browser navigation from Blazor is provided via the NavigationManager service. This can be injected into a Blazor component using @inject in a razor file, or the [Inject] attribute in a CS file. The NavigationManager service has two members that are of particular interest; NavigateTo and LocationChanged .
Blazor applications are component-based. Blazor components can be used in existing ASP.NET MVC applications.
In the Blazor application, a component can also be nested inside another component using the HTML syntax. For example, if you want to nest counter component inside the index component then you need to use <Counter /> within the Index component.
Update:
The error is from WebAssembly, so it is a client-side app. There is no HostingEnvironment on the client and therefore the service is not registered. It would be useless if it was.
So, step back: Why do (you think) you need it?
You should make it a protected or public read/write property:
// in IndexComponent
[Inject]
protected IHostingEnvironment HostingEnvironment { get; set; }
and remove the constructor parameters.
Side note: IHostingEnvironment
is marked as obsolete.
It turns out that for Blazor you need a slightly different interface, namely IWebAssemblyHostEnvironment
.
From this documentation, what you should inject is:
@inject IWebAssemblyHostEnvironment HostEnvironment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With