问题描述
我有以下服务类别:
public class JobService {
private UserService us;
public JobService (UserService us) {
this.us = us;
}
public void addJob(Job job) {
// needs to make a call to user service to update some user info
// similar dependency to the deleteUser method
}
}
public class UserService {
private JobService js;
public UserService(JobService js) {
this.js = js;
}
public void deleteUser(User u) {
using (TransactionScope scope = new TransactionScope()) {
List<IJob> jobs = jobService.findAllByUser(u.Id);
foreach (IJob job in jobs) {
js.deleteJob(job);
}
userDao.delete(user);
scope.Complete();
}
}
}
每个服务类别为可以通过IoC容器实例化,并且没有功能上的问题,但是我觉得这种方法存在潜在的设计缺陷,我想知道是否还有另一种方法更有意义。
Each of these service classes is getting instantiated by IoC container, and there is not a functional problem, but this to me feels like there is a potential design flaw in this approach and I'm wondering if there's an alternative approach that makes more sense.
推荐答案
正如已经指出的那样,问题不在于对DI容器的限制,而与您的设计有关。
As someone already pointed out, the problem is not with limitations to the DI container but with your design.
我知道您拥有单独的 UserService
和 JobService
包含彼此的引用。这是因为 UserService
和 JobService
都包含需要其他服务作为参考的某些逻辑(添加作业需要添加用户等)。但是,我认为您不应引用另一项服务。相反,您应该在服务后面有另一层抽象,这些服务将用于通用逻辑。因此,服务将包含不能(不应)重用的逻辑,而助手将包含共享的逻辑。
I see the reason that you have a separate UserService
and a JobService
which contain a reference to each other. This is because both UserService
and JobService
contain some logic that needs the other service as a reference (adding a job requires adding a user, etc.). However, I think that you should NOT reference one service from the other. Rather, you should have another layer of abstraction behind the services which the services will use for the common logic. So, the services will contain the logic which can't(shouldn't) be reused and the helpers will contain the shared logic.
例如:
public class UserHelper{
//add all your common methods here
}
public class JobService {
private UserHelper us;
public JobService (UserHelper us) {
this.us = us;
}
public void addJob(Job job) {
// calls helper class
}
}
public class UserService {
public UserService(UserHelper js) {
this.js = js;
}
public void deleteUser(User u) {
// calls helper class
}
}
这样,循环引用就不会有任何问题,并且您将拥有一个地方,其中包含需要由不同的人重用的逻辑服务。
In this way, you won't have any issues with circular references and you will have one place which contains the logic which needs to be reused by different services.
此外,我更喜欢拥有彼此完全隔离的服务。
Also, I prefer having services which are completely isolated from one another.
这篇关于依赖注入体系结构设计-服务类循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!