I'm trying to get a good understanding of dependency injection and I see in some cases (Blazor) that it is used at the beginning of the component:
@inject MyHtmlHelper Html
In other cases with the constructor which is the most common:
private readonly IMyHtmlHelper _html;
public MyClaseContructor(IMyHtmlHelper html)
{
_html = html;
}
and in other cases directly on a property:
[Inject]
public IMyHtmlHelper html {get; set;}
My doubt is if the 3 forms are the same or there are differences with the created instances. Thanks.
The idea is the same, it is to get the object of the dependency.
The difference is rather what you can use and what you can't use. There are 2 parts: client and server (host). On the other hand it depends where you are going to use it (.razor or .cs files).
@inject MyHtmlHelper Html
You can only use in .razor files. This format is the most used on the client side.public MyClaseContructor(IMyHtmlHelper html)
You have to use this format in .cs files, which are not partial classes of .razor. For example, you could use it in a service that accesses the database, as a service does not have a visual part in .razor, you would have to insert the dependency in its constructor. This format is the one normally used on the server side.[Inject] public IMyHtmlHelper html {get; set;}
You can use this format in components that have or don't have .razor. This format is mostly used when you create components only with C# without using razor, for example if you want to reinvent InputText component you don't need to use razor, but if you use dependency you would insert it with this method.