Search code examples
c#asp.net-coreblazor

How can I inject a service in blazor only if it exists?


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.


Solution

  • 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();
      }
    }