Access Class library from MVC project?

情到浓时终转凉″ 提交于 2020-01-15 12:15:53

问题


I have a Class Library project and MVC project in the one solution.

My class library has the namespace MyStuff.Classes

My MVC project has the namespace MyStuff.Web

I can't seem to access my class library from the mvc project or vice versa directly or with a using directive??

Whats the best way to use namespaces in this instances? and in general? any hints tips welcome.

Thanks


回答1:


You need to add a reference to your Class project

If you right click on references in your MVC project hit the Projects tab to easily add a reference to your Class project.




回答2:


It depends on where in your MVC project you want to access this class library. First you need to add a project reference to the class library. Accessing it from the Model or the Controller should be trivial.

In order to access it in the view you need to add the following to your web.config:

<pages>
  <namespaces>
    <add namespace="MyStuff.Classes"/>
  </namespaces>
</pages>

Then you can strongly type your view:

<%@ Page Language="C#" 
         MasterPageFile="~/Views/Shared/Site.Master" 
         Inherits="System.Web.Mvc.ViewPage<MyStuff.Classes.MyClass>" %>



回答3:


In the scenario that you have already referenced the Class Library in your MVC project, you may get an error as follows:

Cannot add reference to project because of a circular dependency error

If you try to reference the MVC project in the Class Library. You will not be able to add that project as a reference to your project. The reasoning for this is explained here: Cannot add reference to project because of a circular dependency error

Instead of adding the class to the Class Library project, you can add it to the MVC project. Then all you have to do is add:

using MyStuff.Classes; //Or the name of your class being referenced

You may now use the classes inside of your class library.

This is what I had to do in order to reference a class inside my class library project so I could use the data type "HttpPostedFileBase" because I could not use "System.Web.Abstractions" in my Class Library (it was not being referenced and I could not resolve it with this solution).

I hope this helps if someone runs into this weird scenario.



来源:https://stackoverflow.com/questions/1121543/access-class-library-from-mvc-project

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