简体   繁体   中英

Blazor Dependency injection vs. simple class

I was wondering when I should create a service for my blazor server side app and inject it to the razor components.

What is the difference between a service and a simple class? When should I use a service get get my data instead of a static class method?

Best Marvin

At the top level, you could consider an approach roughly as follows:

  • Use a static class method for simple logic where all the logic can be self contained in that static method. Eg you could use a static method for a RemoveSpacesFromString(string text) method that just acts on the passed in string.
  • Use a service where you have a method that makes calls to other methods, or especially where that method needs to retrieve data from another location (eg a web service) or access a database

Decisions about when to use a class, a static class or a service aren't specifically a Blazor issue, but really relate to concepts like making code testable and allowing substitution of new functionality without having to go back and alter code that is already working.

These are broad topics, if you aren't already up to speed on them you may want to read around Dependency Injection , Unit Testing and the SOLID principles ( this is a Microsoft blog on SOLID that focuses on .NET examples).

Essentially, injecting a service allows for simpler and more focused testing, whereas using a static method means that every time you test the method that calls the static method, you are also testing that static method - that can be either a good or a bad thing, depending on the context and functionality of the static method.

The answer to this is rather simple, you're expected to always get your data from services. Static methods are usually for utility or performance critical logic. However I'm also putting simpler stuff into statics sometimes.

But Services are really not that hard, basically anything can serve as a service, you just handle the logic in an instances and register it as service on app startup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM