I have following Main method. LocalCabelTV and LocalDishTV classes are in the main application program. The program works fine.
I want to keep LocalCabelTV and LocalDishTV in separate dll files. I wonder then how will I load those classes at runtime? I understand then we'll not use switch but for loop to look for all dll files that implements IVideoSource interface in a particular directory and load those...
Need to know how to dynamically load dlls and create objects and use their methods ?
foreach (string dll in Directory.GetFiles("C:\DLLs\*.dll"))
{
Assembly assemb = Assembly.LoadFrom(dll);
??
}
Following works fine:
static void Main(string[] args)
{
SmartTv myTv = new SmartTv();
Console.WriteLine("Select A source to get TV Guide and Play");
Console.WriteLine("1. Local Cable TV\n2. Local Dish TV");
ConsoleKeyInfo input = Console.ReadKey();
switch (input.KeyChar)
{
case '1':
myTv.VideoSource = new LocalCabelTv();
break;
case '2':
myTv.VideoSource = new LocalDishTv();
break;
}
Console.WriteLine();
myTv.ShowTvGuide();
myTv.PlayTV();
Console.ReadKey();
}
class SmartTv
{
IVideoSource currentVideoSource = null;
public IVideoSource VideoSource
{
get
{
return currentVideoSource;
}
set
{
currentVideoSource = value;
}
}
public void ShowTvGuide()
{
if (currentVideoSource != null)
{
Console.WriteLine(currentVideoSource.GetTvGuide());
}
else
{
Console.WriteLine("Please select a Video Source to get TV guide from");
}
}
public void PlayTV()
{
if (currentVideoSource != null)
{
Console.WriteLine(currentVideoSource.PlayVideo());
}
else
{
Console.WriteLine("Please select a Video Source to play");
}
}
class LocalCabelTv : IVideoSource
{
const string SOURCE_NAME = "Local Cabel TV";
string IVideoSource.GetTvGuide()
{
return string.Format("Getting TV guide from - {0}", SOURCE_NAME);
}
string IVideoSource.PlayVideo()
{
return string.Format("Playing - {0}", SOURCE_NAME);
}
}
class LocalDishTv : IVideoSource
{
const string SOURCE_NAME = "Local DISH TV";
string IVideoSource.GetTvGuide()
{
return string.Format("Getting TV guide from - {0}", SOURCE_NAME);
}
string IVideoSource.PlayVideo()
{
return string.Format("Playing - {0}", SOURCE_NAME);
}
}