Recently I moved to MVC 3 and Ninject 2. In most of the code, I use constructor injection, but there are some places, where I had to use Inject
attribute. Ninject 2 registers its own IDepencyResolver
interface. I don't like DependencyResolver
class being part of System.Web.Mvc
namespace, because its function is not really strictly related to MVC, but now, when it is there, I can do
public SomeClass
{
public IUserService UserService { get; set; }
public SomeClass()
{
UserService = DependencyResolver.Current.GetService<IUserService>();
instead of
public SomeClass
{
[Inject]
public IUserService UserService { get; set; }
so I don't have to reference Ninject
namespace in my classes. Should DependencyResolver
be used like that?
I use property injection only for dependencies that are not required for the proper working of the class but could add some functionality if the user sets them. Example of such functionality is logging. So you could have a property which represents a logger where the user can supply his own implementation and if he doesn't the class continues to work normally but it simply doesn't log.
For everything else I use constructor injection. This way you indicate to the consumer that this class has a required dependency on some other service.
So to answer your question about the property injection I would simply have:
and if your class cannot function properly without the user service:
So in both cases no reference to any DI specifics. That's what Inversion of Control is all about.