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
?
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
ITest test
, you only declare it.Test
class doesn't inherit from the interface.You need to update your class declaration
public class Test : ITest // interface inheritance
{
And in your controller, instantiate test
.
ITest test = new Test();
As you get further along, you'll want to explore techniques for injecting the Test
instance into the controller so that you do not have a hard dependency upon it, but just on the interface ITest
. 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With