2

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

Rigobert Song
  • 2,766
  • 2
  • 30
  • 47

3 Answers3

6

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.

Martijn Laarman
  • 13,476
  • 44
  • 63
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>" %>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

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.

Community
  • 1
  • 1
Termato
  • 1,556
  • 1
  • 16
  • 33