Reference vs Dependency

。_饼干妹妹 提交于 2019-12-13 06:50:14

问题


Following on from this question, I now have the following structure:

Wolfie.Core - Contains business logic & entities, also contains repository interfaces (eg IUserRepository) Classes that need to access the repository are using constructor injection.

Wolfie.Data - References Wolfie.Core and has a UserRepository implementing IUserRepository

So I'm happy with this so far. Core doesn't know anything about data implementation and therefore isn't dependent on anything.

The stumbling block I get to is in my Web layer.

My Web project references my Core project. I can then new up a Core class, say User, but I have to pass a concrete implementation of IUserRepository into it. So I need to reference my Data project in my Web project, which seems wrong. It now also looks like Web is dependent upon Data, which it shouldn't be.

So, how can I inject my Core User class with the Data class withouth directly referencing Data?

Look forward to your help.


回答1:


You can bind to interfaces in your main application code, referencing only the contract assembly (the "Core" assembly). Then use reflections to load your dependencies at runtime and inject the concrete classes.

There are a few problems that need to be solved:

  • How you will find the necessary assemblies?
  • What concrete classes should you use, once you've found your assemblies?
  • How will you loosely configure your app to use those assemblies and those concrete classes? You don't want to simply shift your hard-coded assembly references and concrete class references to be hard-coded assembly and class name strings...

These problem can be solved in many different ways, and are one of the main differentiating factors between different Dependency Injection libraries.

Some use top-level configuration code or configuration code modules (for example NInject), some use XML configuration (for example Unity), some use an automatic discovery mechanism based attributes/conventions (for example MAF/MEF), and some use a combination of all of these (for example Castle.Windsor).

Most or all those libraries support each mechanism, but I've mentioned the most prominent focus.



来源:https://stackoverflow.com/questions/9225978/reference-vs-dependency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!