Mabanza
Mabanza

Reputation: 41

Blazor DI works differently in .razor and business class. Why?

In my Blazor server application I can easily instantiate the class, say, DAL class in .razor part:

@page "/"
@inject DAL.DALClass dal

and use it in my @code{} scope.

But if I try to instantiate it in my domain logic class like

public class ServerDesktopDTO : DesktopDTO
    {
        [Inject]
        protected DAL.DALClass dal { get; set; }
...

dal is always null. Why does it work differently? How to inject it to my class using the [Inject] attribute and DI container?

Upvotes: 0

Views: 193

Answers (1)

agua from mars
agua from mars

Reputation: 17444

It works differently because components are created by the render engine and not the DI container.
So the InjectAttribute has been introduced for Blazor and the render engine look for InjectAttribute in components it creates and ask tho the DI contrainer to create the corresponding dependency. But it doesn't look for all classes having InjectAttribute.
In other classes use the constructor injection to provide dependencies if you use the default DI container. Other DI container such as Unity or Autfac can inject dependencies per property or method.

Upvotes: 2

Related Questions