Dependency Injection Architectural Design - Service classes circular references

后端 未结 4 1899
悲&欢浪女
悲&欢浪女 2021-01-15 18:05

I have the following service classes:

public class JobService {
  private UserService us;

  public JobService (UserService us) {
    this.us = us;
  }

  pu         


        
4条回答
  •  太阳男子
    2021-01-15 18:47

    You can decouple the services by using events. Instead of calling a dependent method of another service when an action has been performed, an event is raised. An integrator can then wire up the services through the events. A service does not even know the existence of the other service.

    public class JobService
    {
        public event Action JobAdded;
    
        public void AddJob(User user, Job job)
        {
            //TODO: Add job.
            // Fire event
            if (JobAdded != null) JobAdded(user, job);
        }
    
        internal void DeleteJobs(int userID)
        {
            //TODO: Delete jobs
        }
    }
    
    public class UserService
    {
        public event Action UserDeleted;
    
        public void DeleteUser(User u)
        {
            //TODO: Delete User.
            // Fire event
            if (UserDeleted != null) UserDeleted(u);
        }
    
        public void UpdateUser(User user, Job job)
        {
            //TODO: Update user
        }
    }
    

    The integrator wires up the services

    public static class Services
    {
        public static JobService JobService { get; private set; }
        public static UserService UserService { get; private set; }
    
        static Services( )
        {
            JobService = new JobService();
            UserService = new UserService();
    
            JobService.JobAdded += JobService_JobAdded;
            UserService.UserDeleted += UserService_UserDeleted;
        }
    
        private static void UserService_UserDeleted(User user)
        {
            JobService.DeleteJobs(user.ID);
        }
    
        private static void JobService_JobAdded(User user, Job job)
        {
            UserService.UpdateUser(user, job);
        }
    }
    

    (Note: I simplified event raising a bit. It's not thread safe like this. But you can assume that the events are subscribed in advance and will not be changed later.)

提交回复
热议问题