I have created some services with interfaces and added them as services the ConfigureServices method in the Startup.cs file (see screenshot and code).
public void ConfigureServices(IServiceCollection services)
{
if (Environment.IsDevelopment())
{
EstablishDbContext(services, "DevelopmentConnection");
AddVOMApi(services, "AuthorizationStringsDevelopment");
}
else
{
EstablishDbContext(services, "ProductionConnection");
AddVOMApi(services, "AuthorizationStringsProduction");
throw new NotImplementedException("The production environment has not been implemented.");
}
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddTransient<VomConnection, VomConnection>();
services.AddTransient<IImportInternalHelper, ImportInternalHelper>();
}
When I want to inject the services in a Razor file, my IDE (Jetbrains Rider) adds the @using statements with the path to the classes.
@using Presentation.WebUI.Shared.Components
@using Presentation.WebUI.Shared.Components.Tables
@using Infrastructure.AdapterService.VOM
@using Application.HelperClasses
@inject VomConnection _Vom;
@inject IImportInternalHelper _helper;
In the documentation for Blazor it looks like you do not have to use @using when injecting a service, @inject should be enough.
My code works, but what is wrong with my code since I need to use both @inject and @using? I cannot inject without @using.
@using Presentation.WebUI.Shared.Components
@using Presentation.WebUI.Shared.Components.Tables
@*@using Infrastructure.AdapterService.VOM
@using Application.HelperClasses*@
@inject VomConnection _Vom;
@inject IImportInternalHelper _helper;
Service added in Startup.cs file.
My injections @ using. It works but does not look right, compared to Blazor documentation.
When deleting @using the injections does not work.
I have tried to inject in different ways but the IDE always adds the @using part.
CodePudding user response:
@using
is used to specify to the razor file that you will use a namespace.
It is just used to simplify your code, you can inject your service directly with the full namespace path if you want.
If you don't want to add it to all your razor files, but you use a specific namespace everywhere, you can add it in _Imports.razor
.
However, do not import recklessly all the namespaces in _Imports.razor
this goes against the principle of namespaces and can lead to name conflicts.
CodePudding user response:
@using
used to introduce the namespace of the class(your service) you'd like to inject in your components.