1

I have a razor class library with all my components. I have a class file in the library which i need to inject a service into.

I know i can do it by passing the services in the constructor but I cannot do that.

So I want to know how I can inject a service in a class file with the [Inject] .

I tried inheriting the component class like below but dint work

public class BaseComponent : Component1
{
    
  [Inject]
   public IServerProvider ServerProvider { get; set; }
            
    
    public void Test()
    {
       var server=ServerProvider.Server; // the serverprovider is null here 
       //Note:I cannot use the constructor approrach to load 
    }
}
Steven
  • 166,672
  • 24
  • 332
  • 435
Codegeek
  • 173
  • 1
  • 7
  • 3
    Blazor solely supports property injection through the `[Inject]` attribute for classes that are created by Blazor as Blazor Components. For everything else, you should use constructor injection. – Steven Apr 13 '21 at 10:24
  • Yes of course seems logical and the standard/recmmended way of injecting in Blazor... https://stackoverflow.com/questions/32459670/resolving-instances-with-asp-net-core-di-from-within-configureservices Found this post if it helps anyone using a lot of services but is of course anti pattern – Codegeek Apr 14 '21 at 10:05
  • Can you provide more datails? What is `BaseComponent`? What is `Component1`? Have you tried inheriting from `ComponentBase`? – Grizzlly Apr 14 '21 at 13:38
  • Basecompoenent is a simple class file and component1 is a partial class of a razor component which I have tried to inherit to be able to use the [inject] but no luck.....Yes i tried inheriting from componentbase but I cannot use the inject attribute with the property to inject in a class even though it inherits from component base.I am now using the constructor approach to pass the services since that is the only standard blazor way of doing it. – Codegeek Apr 15 '21 at 13:45

0 Answers0