0

I have a Service with a business object (bo), that implements an interface. The bo implements an interface too. How can I declare an interface, that describes the service and also the bo?

Here some Code:

// Business object with interface
public interface IBoBase { }
public class Bo : IBoBase { }

// Service with interface
public interface IService<TBo> where TBo : IBoBase
{
    TBo Get();
    void Set(TBo bo);
}
public class Service : IService<Bo>
{
    private Bo _bo;
    public Bo Get(){return _bo;}
    public void Set(Bo bo) { _bo = bo; }
}

// Usage
public class SubService
{
    private readonly List<IService<IBoBase>> _injectedService;
    public SubService(Service injectedService)
    {
        _injectedService = new List<IService<IBoBase>>
            {
                injectedService // cannot cast to IService<IBoBase> ... why?
            };
    }
}

Does anyone have an idea, how to design the interface, so I can use it like described in the code example?

Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85
Benjamin Ifland
  • 137
  • 1
  • 10
  • Possible duplicate of [Nested Interfaces: Cast IDictionary> to IDictionary>?](http://stackoverflow.com/questions/10399568/nested-interfaces-cast-idictionarytkey-ilisttvalue-to-idictionarytkey-ie) – Vijay Kumbhoje Jul 18 '16 at 12:32
  • You `Service` class doesn't implement `IService`, so why do you expect that you can cast it to that? `IService` is not equal to `IService where TBo: IBoBase`. – Maarten Jul 18 '16 at 14:17
  • And this is exactly my problem and question. How can I describe my Service with a typed BO as an interface. Are there any tricks with co- oder contravariance? – Benjamin Ifland Jul 19 '16 at 07:19

1 Answers1

0

Right casting find below, alos i am not sure this what you have expecting?.

public class SubService
{
    private readonly List<IService<IBoBase>> _injectedService;
    public SubService(*IService<IBoBase>* injectedService)**
    {
        _injectedService = new List<IService<IBoBase>>
        {
            injectedService 
        };
    }
}
Raj A
  • 141
  • 1
  • 6
  • No, my service is injected by Autofac, so I need to specify the Service directly. Otherwise I have the casting problem in the Autofac, where I cannot register my Service as IService. – Benjamin Ifland Jul 18 '16 at 13:00