Unity framework DependencyAttribute only works for public properties?

前端 未结 8 1227
小鲜肉
小鲜肉 2021-02-14 17:31

I was trying to clean up some accessability stuff in my code, and inadvertently broke Unity dependency injection. After a while I realized that I marked some public properties t

8条回答
  •  难免孤独
    2021-02-14 17:54

    The question itself seems to be a misunderstanding.

    Regarding the core statement:

    a bunch of public properties that you never want anyone to set or be able to set, other than Unity.

    You would want to set them in unit tests, or how else would you pass dependency mocks? Even if you don't have unit tests, it's a strange idea to have dependencies that nothing (except some magic of Unity) can set. Do you want your code to depend so much on support tool?

    Also, having public properties is not an issue at all, because your code MUST depend on interfaces, not on implementations (one of SOLID principles). If you don't follow this principle - there is no reason for you to use Unity. Surely you wouldn't declare dependencies in the interface, so the consuming class doesn't know about them.

    You've already been told that it's better to use constructor injection, but property injection also has its beauty. It allows adding new dependencies with less modifications (in particular, you can avoid changing existing unit tests at all, only adding new ones).

提交回复
热议问题