Sharing Code and Resources (Part 2)

 




Cleaning Up The Shared Files

Let's make sure the moved files have matching namespaces:

  • In the MyBlog.Shared project, change the namespace to MyBlog.Shared. Components on the following files-

Components/BootstrapFieldCssClassProvider.cs

Components/ CustomCssClassProvider.cs

  • Remove @using MyBlogServerSide.Components from the following files-

Pages/Admin/BlogPostEdit.razor Pages/Admin/BlogPostList.razor Pages/Admin/CategoryList.razor Pages/Admin/TagList.razor

  • In the MyBlog.Shared project, add the following namespaces to the _Imports.razor file-

@using MyBlog.Shared

@using MyBlog.Shared.Components

We have cleaned up a couple of new projects.

Adding The API

Perform the following steps:

  • In the MyBlogWebAssembly.Client project, open Program.cs and add the following-

builder.Services.AddScoped <IMyBlogApi>;

MyBlogApiClientSide >();

  • Add the following namespaces at the top of the file-

using MyBlog.Data;

using MyBlog.Data.Interfaces;

  • Delete the Pages/Index.razor file (since we will be getting that one from our shared library instead).

  • The same goes for Shared/NavMenu.razor. Delete that file as well.

  • Open App.Razor and, in the router component, add the following as an additional property-  

AdditionalAssemblies="new[] { typeof(MyBlog.Shared.Pages. Index).Assembly}"

  • This is telling the router to look for matches in the current project, but also in the MyBlog.Shared assembly.

  • Add the following namespaces to _Imports.razor-

@using MyBlog.Shared

@using MyBlog.Shared.Shared

  • In the MyBlogWebAssembly.Server project, open the Startup.cs file and replace services.AddControllersWithViews().

  • Set MyBlogWebAssembly.Server as the start-up project by right-clicking the project and selecting Set as Startup Project and pressing Ctrl + F5.

  • You should now see blogposts getting listed and you should be able to navigate to a blog post by clicking the link.

Conclusion

We now have the same Blazor components running in Blazor Server as well as Blazor WebAssembly.

















Comments