views:

63

answers:

2

Here is the situation:

ICategorized is used by ICategoryService to manage categories

public interface ICategorized
{
    ICategory Category { get; set; }
}

Then some class implements ICategorized.

public class Cart : ICategorized
{
 ...
 ICategory Category { 
 get {
    return _categoryService.GetItemCategory(...)
 }
 set {
   _categoryService.SetCategoryForItem(...);
};

}

... }

So, what is the best solution to set _categoryService implementation? Through constructor or property injection?

Using of constructor can lead to very complex constructor like

public class Cart : ICategorized. ITagged, ISecured, IMediaSupport {
public Cart(ICategoryService cs, ITagService ts, ISecurityService ss, IMediaService ms) {...}

... }

I doubt this is a good design. Any ideas?

+3  A: 

I favor constructor injection over property injection, mainly because it makes explicit what services the component requires. If you use an IoC-container you wouldn't have to worry about the constructor getting too complicated since you never have to use the constructor, only the container does.

Property injection could be used for non-required services.

By the way; generally speaking, very long constructor signatures probably means that your class does not adhere to the single responsibility principle and perhaps it should be refactored into two or more separate classes.

Patrik Hägne
+1 was going to add an answer, but this sums it up pretty well.
eglasius
A: 

What would be your suggestion? I can give to CartService responsibility of ICategoryService but in that case I can't use Lazy loading. Something like

public class CartService : ICartService {
public CartService(ICategoryService cs) {...}

...

}
Andrej Kaurin
Andrej, stackoverflow works slightly differently to a conventional forum - you should respond either in a comment to the specific answer rather or by editing your question to add detail.
Murph