Reputation: 1111
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?
Upvotes: 1
Views: 152
Reputation: 1064204
Two thoughts occur:
partial
to have the service / interface parts of the type in separate files (since the code mentions partial
and doesn't seem to implement the interface itself) are the namespaces correct? With partial
classes it is perilously easy to accidentally end up creating two types rather than one typeIRiskFactory
suffering from resolution issues (perhaps from having a referenced dll and a local copy)? i.e. is all the code talking about the same IRiskFactory
?Upvotes: 2
Reputation: 39956
Shouldnt your windows service class actually implement service like below ...
public partial class RiskFactoryService : ServiceBase , IRiskFactory
{
}
and why are you creating RiskFactoryService in constructor of RiskFactoryService, i think this will give stack overflow error !! You can simply call , this.StartService()...
Upvotes: 2
Reputation: 29
I think the problem is that in this case RiskFactoryService is referring to the partial class definition RiskFactoryService : ServiceBase which does not implement IRiskFactory (did you mean that class to be the same as the RiskFactoryService class that does implement IRiskFactory? - if so that class definition should probably be marked partial as well).
A more pressing problem I see is that you are recursively calling the constructor for the RiskFactoryService class inside itself. This means that every time you try to instantiate a RiskFactoryService the stack will overflow.
Upvotes: 0