问题
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