Add a dependency / reference to your own DLL proje

2019-06-20 14:59发布

问题:

I have been working on a few different applications and I want them all to share the same DLL library. The shared DLL is one that I created, so really I want each application to have a dependency on the DLL so that the DLL gets built in the same solution as the application. Then the DLL should copy itself to the application's bin folder before the application runs.

After figuring out how to do this, it seems that it should have only taken about 5 minutes, but unfortunately it took me an hour to figure out. That's partly because similar questions were referring to older versions of Visual Studio, or referring to 3rd party DLLs. So I thought I'd post the steps here.

回答1:

  1. You should already have one existing project and solution for your DLL. Open your solution for your new application that depends on your DLL
  2. Highlight the top line in your Solution Explorer (your solution name), then go to the File menu and choose Add > Existing Project...
  3. Browse to the project file for your DLL and select it. That will add the DLL project to your solution
  4. Although your projects are now in the same solution, that didn't actually create a reference for your main project. So now right-click on your original project (should be 2nd line in your Solution Explorer) and choose Add > Reference...
  5. The Reference Manager will appear. Be sure that you have Solution > Projects selected on the left. Then you should see your DLL project listed on the right. When you hover over it, a checkbox will appear. Select the check box. Click OK.
  6. Last, be sure that your Project Dependencies are set correctly. Again, right-click on your Solution in Solution Explorer (top line). Choose Project Dependencies...
  7. In the Projects drop down, make sure your main project is selected. Then in the Depends On list below, check the box for your DLL project.

Now when you Build your solution, it will first build the DLL, then copy it to your applications bin folder, then build your application. The Reference will also allow you to refer to the DLL in your code files, for example with "using MyLib;" for C#, or "Imports MyLib" for VB