Using static classes in a business logic layer

I know that the answer to my question may include choosing a specific approach, but I'm trying to explain what I'm trying to find out with details:

Consider a simple three-layer application (DAL, BLL, PL).
DAL uses EF 4.1 Code-First, and data access ends in the repository.

Right now, in BLL, I have Manager classes. (e.g. UserManager , ProductManager ) that all get from BaseManager . Almost every method in my Manager classes accepts a related object as a parameter and performs the corresponding operations on it. for example, in the UserManager (Pseudocode):

 public bool AddPermission(User user, PermissionItem permission) { this.repository.Add(permission); this.save(); } 

Question: My manager classes do not have to be created. they can be defined as static. But if I define them static, I have to create my common methods and members (e.g. repository and several other members) in each class (I don't want to define elements such as a repository, like static).

So, you suggest me to change the manager classes that really should be static for static classes? or is it ok to use them like them?

+4
source share
3 answers

The imho static classes are nothing more than containers for functions (not real objects). The difference is that non-static classes can be inferred and get their dependencies through the constructor.

Try writing the right tests for a static class.

You may not have planned for them to be today, but what about tomorrow? If you change them to static, you will have to reorganize all your dependent codes to static ones.

I would prefer to use the inverse of the control container to control their creation and instances.

+4
source

I see no reason to make them static. As far as I can see, this will only complicate the API and implementation. And where would your subscribers get the repository from? Should they look for them for every call? It is wasteful. It is much better to deal with him and keep him in the manager. These are instance variables.

+2
source

I like to create a static "directory" (the correct name for this object is actually a repository) that contains all my instances. For instance:

 public static Class BusinessRepository { private static Users users = new Users(); public static Users Users { get { return users; } } } 

The BusinessRepository class is static, but Users are the instance object contained in it. This can then be obtained as follows:

 BusinessRepository.Users.DoSomething(); 

This way you can save instances of objects and all the benefits they bring with static access to them.

Many people disagree with such "global variables" as they call them, but this is your call to judgment. It looks like you have already decided that you are happy with this, since you are already talking about static classes.

0
source

All Articles