0

I've seen two ways to inject dependency with Unity.

With Constructor :

private readonly IDummyService _dummyService;

public AuthController(IDummyService dummyService)
{
    this._dummyService = dummyService;
}

With Attribute :

[Dependency]
public IDummyService _dummyService { get; set; }

public AuthController()
{
}

What is the difference between these two approaches? and which one is better to use?

hendryanw
  • 1,819
  • 5
  • 24
  • 39
  • 2
    You will find a lot of info on this question http://stackoverflow.com/questions/1503584/dependency-injection-through-constructors-or-property-setters – Amr Elgarhy Apr 03 '15 at 09:14
  • 1
    I don't think there are a lot of differences. I like the constructor call personally though, because you can always check if you don't get null (and not a nullrefexception elsewhere). – Caramiriel Apr 03 '15 at 09:14
  • thanks for the link! I cannot find it earlier – hendryanw Apr 03 '15 at 09:17
  • 1
    Always choose constructor injection. Otherwise you're introducing a tight coupling between your code and DI container you use. – Sriram Sakthivel Apr 03 '15 at 09:19
  • @SriramSakthivel : I prefer using constructor injection. But the other forms of injection have their merit too (preventing circular dependencies for instance) – Falanwe Apr 03 '15 at 10:28
  • @Falanwe But that's a problem. In first place you should design your classes in such a way that it doesn't require circular dependency. If it is unavoidable, use property injection(But not using the attributes). Using attributes couples your code with DI container; If you want to replace your container tomorrow, you're in trouble. – Sriram Sakthivel Apr 03 '15 at 10:39

0 Answers0