I have a class that implements an interface. The interface is
public interface IRiskFactory
{
void StartService();
void StopService();
}
The class that implements the interface is
public class RiskFactoryService : IRiskFactory
{
}
Now I have a console application and one window service.
From the console application if I write the following code
static void Main(string[] args)
{
IRiskFactory objIRiskFactory = new RiskFactoryService();
objIRiskFactory.StartService();
Console.ReadLine();
objIRiskFactory.StopService();
}
It is working fine. However, when I mwrite the same piece of code in Window service
public partial class RiskFactoryService : ServiceBase
{
IRiskFactory objIRiskFactory = null;
public RiskFactoryService()
{
InitializeComponent();
objIRiskFactory = new RiskFactoryService(); <- ERROR
}
/// <summary>
/// Starts the service
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
objIRiskFactory.StartService();
}
/// <summary>
/// Stops the service
/// </summary>
protected override void OnStop()
{
objIRiskFactory.StopService();
}
}
It throws error: Cannot implicitly convert type ‘RiskFactoryService’ to ‘IRiskFactory’. An explicit conversion exists (are you missing a cast?)
When I type cast to the interface type, it started working
objIRiskFactory = (IRiskFactory)new RiskFactoryService();
My question is why so?
Two thoughts occur:
partialto have the service / interface parts of the type in separate files (since the code mentionspartialand doesn’t seem to implement the interface itself) are the namespaces correct? Withpartialclasses it is perilously easy to accidentally end up creating two types rather than one typeIRiskFactorysuffering from resolution issues (perhaps from having a referenced dll and a local copy)? i.e. is all the code talking about the sameIRiskFactory?