Reputation: 31655
If I use Inject
attribute and try to inject service that isn't registered, it gives me the error There is no registered service of type X
.
So how can I inject a service without giving me this error, and if the service isn't injected, the service will be just null. Is this possible?
e.g.
This will give me an error if Foo
isn't registered.
[Inject]
protected Foo Foo { get; set; }
But I want to allow that Foo
isn't registered and in that case it will be null
.
Upvotes: 6
Views: 2239
Reputation: 23224
You can do this
@using Microsoft.Extensions.DependencyInjection
@inject IServiceProvider ServiceProvider
@code
{
private IMyService MyService;
protected override void OnInitialized()
{
MyService = ServiceProvider.GetService<IMyService>();
base.OnInitialized();
}
}
Upvotes: 10
Reputation: 602
This question might make sense if you wanted to access server side data but only if blazor was prerendering on the server side (Blazor WebAssembly App (ASP.Net Core Hosted)).
In situations like this you might be registering services in the ASP.Net app Startup.cs and the Blazor WebAssembly entry point Program.cs.
In cases like this you can create a interface for the functionality you are wanting to access:
namespace BlazorApp1.Client {
public interface IResponse {
void SetNotFound();
}
}
Have one instance of the interface that does nothing, or returns empty results which can be registered for the Program.cs:
namespace BlazorApp1.Client {
public class ResponseStub : IResponse {
public void SetNotFound() {
// Do nothing if we are browser side
}
}
}
And another instance that does the work with the instance setup in Setup.cs:
using BlazorApp1.Client;
using Microsoft.AspNetCore.Http;
using System.Net;
namespace BlazorApp1.Server {
public class Response : IResponse {
private readonly IHttpContextAccessor _httpContextAccessor;
public Response(IHttpContextAccessor accessor) {
_httpContextAccessor = accessor;
}
public void SetNotFound() {
_httpContextAccessor.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
}
}
}
Upvotes: 0