Search code examples
asp.net-coreblazor.net-8.0

How dotnet know where _Imports.razor is?


When creating Blazor project with dotnet new blazor _Imports.razor get created in Components directory. It's working fine.

I've server-side Blazor project "mutated" gradually from .NET Core 3.x to .NET 8 mostly by using upgrade-assistant command. _Imports.razor is in the root directory of project and it's also working fine. I want to try to "modernize" this project structure to something resembling dotnet new blazor template.

I tried moving even just _Imports.razor to Components directory (in Program.cs I've added using Project.Components;) but this operation breaks whole application horribly (a lot of unknown namespaces).

What further puzzles me is that I can move _Imports.razor to root directory in new Blazor project and it's still working fine. How this is possible? What determines where _Imports.razor can be and where not?


Solution

  • We have a section which containing description like below:

    Every folder of an app can optionally contain a template file named _Imports.razor. The compiler includes the directives specified in the imports file in all of the Razor templates in the same folder and recursively in all of its subfolders. Therefore, an _Imports.razor file containing @layout DoctorWhoLayout ensures that all of the components in a folder use the DoctorWhoLayout component. There's no need to repeatedly add @layout DoctorWhoLayout to all of the Razor components (.razor) within the folder and subfolders.

    In other words, .net will check each folder to get the _Imports.razor in blazor project to make sure all the components in a folder could reuse the reference. I had a test in my side, which using a component defined in RCL in my main blazor server application. We know that it requires to write like <ComponentLibrary.Component1 /> or @using ComponentLibrary <Component1 />.

    If we put @using ComponentLibrary in the root _Imports.razor, we can still write <Component1 />. The same if we create a sub _Imports in Pages folder. But if I create another component which is put under the root folder, only the configuration in root _Imports could make it work.

    enter image description here

    ===========================

    Deleting the root _Import.razor

    enter image description here