Reputation: 732
I have two Interfaces in different projects (these projects are not referenced to each other) which have the same methods like this:
In first project we have:
public interface IInterfaceA
{
IAViewModel Do();
}
public interface IAViewModel
{
int Id { get; set; }
}
public class ServiceA : IInterfaceA
{
public IBViewModel Do()
{
return null;
}
}
In second project we have:
public interface IInterfaceB
{
IBViewModel Do();
}
public interface IBViewModel
{
int Id { get; set; }
}
I can create an instance of ServiceA at runtime, using some Reflection, from second project.
The question is that how can I convert that service to IInterfaceB. I mean I want to access it's methods when someone is developing by referring as IInterfaceB .
Upvotes: 0
Views: 68
Reputation: 70701
If I understand your updated question correctly, the fact that ServiceA
class implements IInterfaceA
is irrelevant to the question (you don't even know the implemented member).
As far as the question you seem to be asking — is it possible to treat an instance of ServiceA
as if it were an instance of an implementation of IInterfaceB
— the answer to that question is "no".
However, you can approximate that result, in one of at least two ways:
dynamic
type. Here, the object won't be visible as IInterfaceB
, but you can at least call the Do()
method via a variable typed as dynamic
.ServiceA
in an adapter class, which does implement IInterfaceB
, and which delegates its implementation to the instance of ServiceA
. Then you can use the instance of the wrapper class where you need an object that implements IInterfaceB
.For example:
class BAdapter : IInterfaceB
{
private readonly ServiceA _serviceA;
public BAdapter(ServiceA serviceA)
{
_serviceA = serviceA;
}
public IInterfaceB Do() { return _serviceA.Do(); }
}
You could alternatively declare _serviceA
(and the constructor parameter too) in the above example as dynamic
, and achieve the same result.
Upvotes: 1