Say I have an Interface like this in a project called "Interface":
public interface TestInterface
{
string Operation();
}
and class which implements it. This class is located in another project "Class":
public class TestClass : TestInterface
{
public TestClass() { }
public string Operation()
{
return "This is an Operation";
}
}
My client does something like this (which is again in a different project "Client"):
class Program
{
static void Main(string[] args)
{
TestInterface i = new TestClass();
i.Operation();
}
}
My question is related to this line:
TestInterface i = new TestClass();
By adding this line, I'm actually forced to add a references to both "Interface" as well as "Class" projects from my "Client" project. So why all this fuss? Can't I directly refer to the "Class" without keeping the "Interface" in between? Is there any way to access the methods via Interface only (without making a reference to the implementation Class)? Am I missing something here?
To make your code completely independent from implementation of
TestInterface
use Dependency Inversion. This could be achieved by some Dependency Injection framework.E.g. with Unity you can configure implementation via xml
And your code will depend only on Unity (no references to implementation):
You have interface so that your app can have
plug in's
..So basically you share your Interface dll to anyone who wants to make a plugin app for your app and then you can cast that new plugin class to the interface and invoke methods on it..
If you dont cast the class to the interface,how on earth are you going to make the plugin class work for your app..
In that particular sample, there is no advantage.
But imagine a method:
Now,
Foo
operates only on the interface and it doesn't care what concrete class implements this interface. You could now callFoo
with an instance ofTestClass
or withTestClass2
, which could be defined in a different assembly.you can achieve the behavior you have described via using IOC. Unity is a dependency injection container which allows to create instances without manually creating instances.
For instance, if you were to register your class and interface to unity, you would directly use the interface;
Yes, there is. You can dynamically load an assembly with
TestClass
without referencing it, create its instance viaActivator.CreateInstance
and cast it to interface type:...or... you may use one of existing DI-frameworks (e.g. MEF) and do the same thing more right way:
or:
Depending of the way you prefer, you may ask more concrete question.