Here is the situatio开发者_如何学Cn:
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?
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) {...}
...
}
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.
精彩评论