locked
Design Question - Using same class on both client and server RRS feed

  • Question

  • User1168746228 posted

    Hi,

    I hope this isn't a dumb question.  I have a web application, written in Blazor, that calls a RESTful web API.  I want to share classes on both the client and the server, but some functionality is needed on the server only and some on the client only.  What's the best way of doing this (or is there a better approach)?  Would I create an abstract base class that contains all the common elements and then create concrete classes for both a client version and a server version?  For example, I have a GameUpdate class that's used on both the client and the server that has a Save to database method that's only applicable when it's on the server.

    Thanks.

    Tuesday, January 5, 2021 10:00 PM

All replies

  • User-474980206 posted

    The api classes should be poco objects with no methods. Then use extension methods instead. You can have common, client and server extension methods.

    Wednesday, January 6, 2021 2:08 AM
  • User1686398519 posted

    Hi edhalsim, 

    Would I create an abstract base class that contains all the common elements and then create concrete classes for both a client version and a server version?

    You can create a .NET standard class library project called BlazorDemo.Models in the same solution.

    After adding references to the BlazorDemo.Models project from the Blazor Web application project and ASP.NET Core RESTful service, you can use these model classes(in the BlazorDemo.Models project) in the Blazor Web application project and ASP.NET Core RESTful service.

    I found a tutorial with detailed examples, you can click this link to view it, it should be helpful to you.

    Best Regards,

    YihuiSun

    Wednesday, January 6, 2021 3:20 AM
  • User1168746228 posted

    I like this idea.  How would you handle properties or private variables that the class needs on say the server, but not the client?

    Wednesday, January 6, 2021 3:23 PM
  • User-474980206 posted

    You can use partial classes or inheritance to add private properties to the server version. But it sounds like you want to break SOC and tightly bind the client and server code. You really should be using interfaces and extension methods.

    Wednesday, January 6, 2021 3:52 PM