I'm using dependency injection in my C# projects and generally everything is ok. Nevertheless, I often hear the rule "constructor must only consist of trivial operations - assign dependencies and do nothing more" I.e:
//dependencies
interface IMyFooDependency
{
string GetBuzz();
int DoOtherStuff();
}
interface IMyBarDependency
{
void CrunchMe();
}
//consumer
class MyNiceConsumer
{
private readonly IMyFooDependency foo;
private readonly IMyBarDependency bar;
private /*readonly*/ string buzz;//<---question here
MyNiceConsumer(IMyFooDependency foo, IMyBarDependency bar)
{
//omitting null checks
this.foo = foo;
this.bar = bar;
//OR
this.buzz = foo.GetBuzz();//is this a bad thing to do?
}
}
UPD: assume IMyFooDependency
can't be replaced with the GetBuzz()
, as in that case the answer is obvious: "do not depend on foo
".
UPD2: Please, understand that this question is not about eliminating dependency from foo in a hypothetic code, but about understanding a principle of good constructor design.
So, my questions is following: is this really a bad pattern to include non-trivial logic in constructor(i.e. obtaining buzz
value, making some calculations based on dependencies.)
Personally I, unless lazy load is necessary, would include foo.GetBuzz()
in constructor, as object need to be initialized after call to its constructor.
The only drawback I see: by including non-trivial logic you increase the number of places where something might go wrong, and you'll get an obfuscated error message from your IoC container(but same things happen in case of invalid parameter, so the drawback is rather minor)
Any other considerations for eliding non-trivial constructors?