开发者

.NET MVC Controller with multiple Repositories and Services?

Look at my Controller (I'm using Dependency Injection to manager dependencies):

public RoleController(IRoleRepository roleRepository, ISiteRepository siteRepository, IUserRepository userRepository, IDbContext dbContext)
{
    _roleRepository = roleRepository;
    _siteRepository = siteRepository;
    _userRepository = userRepository;
    _dbContext = dbContext;
}

Having a class with many dependencies is a code smell? Right?

But, In my example I need to associate Users and Sites in a Role, then I need to these dependencies to doing this association.

Some people on a mailing list I was told that having too many dependencies is a sign that something is probably wrong. But I see no other way. I separated my responsibilities, there is something in that situation I do not know how to treat? Is something wrong?

Update:

I need Repositories and DbContext because DbContext is my UnitOfWork, repositories don't save.

This example is a simple CRUD with some other functionalities like Associations in the View with a GRID.

Update 2:

I'm using a ar开发者_JAVA技巧chitecture where my UI Layer is the MVC.


I don't believe it's a bad thing, given that you manage dependencies with a good DI framework (i.e. not by using poor man's DI). This way, you explicitly say that the controller will need all these things, because it will. (Note that in many other parts of your application, this might not be a valid argument - the controller is special in the way that it is where you control and direct the program flow, so there's a natural explanation why it needs to see lots of parts of the application...)

However, if you really want to limit the number of dependencies in this specific case, it could make sense to create a MembershipService, which does all the work concerned with Users, Sites and Roles. That would then have a dependency on those three repositories, and your controller would only have a dependency on the membership service.


In response to your update: You could register the unit of work (i.e. the db context) as a "per web request" singleton - this is possible with Castle Windsor and many other DI frameworks. Then you can let your repositories depend on it and do all the changes, and let the controller depend on it for saving, and they will all get the same instance handed to them by the DI framework.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜