what is the difference from static class and dependency injection?

mc 5,491 Reputation points
2024-11-19T15:53:35.9166667+00:00

creating static partial class and then create partial class in platform/android folder.

vs

creating interface and then create the real class which inherit the interface in platform/android forlder.

what is the difference?

Developer technologies | .NET | .NET MAUI
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Taylor 60,326 Reputation points
    2024-11-19T16:21:31.7766667+00:00

    Can you provide us the context of your question? It is hard to understand what you're trying to do.

    In academic terms a static class is a class that contains nothing but static members as discussed here. A static member is used when the member does not need any instance-level data to do its work. In other words it provides some global functionality (or data) that can be used without first creating an instance of a class. Common utility functions like Math.Max and DateTime.Today are good examples. They just rely on data given to them as parameters or they work against data that is global to the application. Honestly a static class is just a design decision to ensure that a class that shouldn't have instance members doesn't accidentally get created as one. Ultimately what you have to decide, for each member of a class, is whether it should be static or instance member. You can read more about that here.

    DI involves using types in code without knowing the actual implementation of that type in advance. DI decouples the creation of a dependency from its usage. You can read more about it here. Static classes cannot be part of DI because DI requires the DI container to create an instance of the dependency. Since static classes don't have instances then DI doesn't apply here. You can just use static classes directly in the code that depends on it.

    Without an understanding of what you're trying to understand/figure out it is hard to provide more clear differences.

    1 person found this answer helpful.
    0 comments No comments

  2. Bruce (SqlWork.com) 77,926 Reputation points Volunteer Moderator
    2024-11-19T17:05:38.7766667+00:00

    static classes have no instance data, do not support inheritance and as such are unrelated to DI which is a pattern to abstract object creation.

    dependency injection uses a factory to create an instance of class. in the case of Maui, the class instance is injected via the constructor, by a factory that creates the class and manages the DI objects.

    with DI you can use either interfaces or inheritance to define the injected object instance properties and methods. as .net does not support multiple inheritance, interfaces are more flexible and the standard practice for DI.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.