I have a service assembly with multiple service classes. Each class groups a set of related service methods. These services are instantiated using IoC and constructor injectors.
If I have two service classes that may, at times, need to call methods in the other, what is the best way to handle these in order to avoid circular references?
For example, assume the two service methods from two different service classes (not necessarily the most practical example, but for simplicity's sake):
public class UserService
{
public void RegisterUser(User user)
{
// Do a bunch of stuff needed to register a user
// Now call out to permission service to set up basic permissions
_permissionService.SetUpBasicPermissions(user);
}
}
public class PermissionService
{
public void GrantPermission(User user, int PermissionId)
{
// Add user permission to database
// Now call out to user service to do some other stuff on the user
_userService.TakeActionsOnUserAccount(user);
}
}
Here are the options I can see:
Considering functionality needs to be shared between the two, this is a sign the service classes should be merged into one class. If this is the case, though, might I ultimately end up with one giant service class? What determines how they should be split up?
Don't combine both classes, but move methods that share logic into their own service class (leaving the user and permission specific logic in their individual classes). If this is the case, I may end up with several of these shared services, and I'm thinking that's not a good thing.
Any actions needed from one service into another should be moved to the calling code. This seems problematic to me, since I would be removing potentially dependent logic, and making it another layer's concern. In other words, where ever I call _userService.RegisterUser(), I will now always have to call _permissionService.SetUpBasicPermissions() immediately following every call.
Allow one service to call the other, but not both. If this is the case, which one do I choose? What do I do w/ the logic for the one that can't call the other?
Use delegates to inject dependent service methods into the called service methods. Bleh, this sounds ugly.
Those are the ones I can think of, but I'm sure there are some I'm overlooking.
Thoughts?
Thanks in advance.