This is a relatively straight forward question. But I was wondering what the correct usage is for accessing a method inside a separate project through the use of an interface.
Project: Test.ClassLibrary
Interface:
public interface ITest
{
string TestMethod();
}
Class:
public class Test : ITest
{
public string TestMethod()
{
return "Test";
}
}
Project: Test.Web
Controller:
public class HomeController : Controller
{
private ITest test;
public ActionResult Index()
{
return Content(test.TestMethod());
}
}
The above returns a NullReferenceException. I’m assuming it’s because the controller gets to the interface, and doesn’t know where to go next.
What’s the best way to fix this? Do I have to reference the Test class in the controller or can I some how get away with only having a reference to ITest?
ITest test, you only declare it.Testclass doesn’t inherit from the interface.You need to update your class declaration
And in your controller, instantiate
test.As you get further along, you’ll want to explore techniques for injecting the
Testinstance into the controller so that you do not have a hard dependency upon it, but just on the interfaceITest. A comment mentions IoC, or Inversion of Control, but you should look into various Dependency Inversion techniques techniques (IoC is one of them, dependency injection, etc).