I am trying to understand TDD more and all the examples I have seen regarding DI have been classes/interfaces that only have methods on them eg.
public interface IUserRepository
{
User GetByID(int ID);
}
public class UserRepo : IUserRepository
{
private IUserRepository Repo;
public UserRepo(IUserRepository repo)
{
this.Repo. = repo;
}
public User GetByID(int ID) {}
}
.....
private void SetupDI()
{
container.Register<IUserRepository>.With(UserRepository);
}
I recently started writing an interface with properties on it and stopped as was unsure how this would be accomplished.
Is having properties in interfaces OK in terms of DI? Is it good design?
I would assume that these properties would be injected like so:
private void SetupDI()
{
var myStringProp = GetPropValue("MyStringProp");
var myIntProp = GetPropValue("MyIntProp");
container.Register<IUserRepository>.With
(
new UserRepository() {
StringProperty = myStringProp;
IntProperty = myIntProp;
}
);
}
OR
Would you pass all the required properties in the constructor:
private void SetupDI()
{
var myStringProp = GetPropValue("MyStringProp");
var myIntProp = GetPropValue("MyIntProp");
container.Register<IUserRepository>.With
(
new UserRepository(myStringProp,myIntProp)
);
}
It’s perfectly fine to use properties in interfaces, but your question is really mainly about constructor vs. property injection and not so much about using properties in interfaces.
The former (constructor injection) is clearly preferred since the dependencies of a class must be passed in at the time of creation, so they are clearly visible and not “hidden”. Personally I aim to always use constructor injection, and property injection only as a last resort, e.g. when there is a cyclic dependency that otherwise cannot be resolved (at that time it is probably better to rethink the design).