C# – Should interfaces extend (and in doing so inherit methods of) other interfaces

cdesigninterfaces

Although this is a general question it is also specific to a problem I am currently experiencing. I currently have an interface specified in my solution called

public interface IContextProvider
{
   IDataContext { get; set; }
   IAreaContext { get; set; }
}

This interface is often used throughout the program and hence I have easy access to the objects I need. However at a fairly low level of a part of my program I need access to another class that will use IAreaContext and perform some operations off it. So I have created another factory interface to do this creation called:

public interface IEventContextFactory 
{
   IEventContext CreateEventContext(int eventId);
}

I have a class that implements the IContextProvider and is injected using NinJect. The problem I have is that the area where I need to use this IEventContextFactory has access to the IContextProvider only and itself uses another class which will need this new interface. I don't want to have to instantiate this implementation of IEventContextFactory at the low level and would rather work with the IEventContextFactory interface throughout. However I also don't want to have to inject another parameter through the constructors just to have it passed through to the class that needs it i.e.

// example of problem
public class MyClass
{
    public MyClass(IContextProvider context, IEventContextFactory event)
    {
       _context = context;
       _event = event;
    }

    public void DoSomething() 
    {
       // the only place _event is used in the class is to pass it through
       var myClass = new MyChildClass(_event);
       myClass.PerformCalculation();      
    }
}

So my main question is, would this be acceptable or is it even common or good practice to do something like this (interface extend another an interface):

public interface IContextProvider : IEventContextFactory

or should I consider better alternatives to achieving what I need. If I have not provided enough information to give suggestions let me know and I can provide more.

Best Answer

While interfaces describe only behavior without any implementation, they can still participate in inheritance hierarchies. As an example, imagine you have, say, the common idea of a Collection. This interface would provide a few things that are common to all collections, such as a method to iterate over the members. Then you can think about some more specific collections of objects such as a List or a Set. Each of these inherits all the behavior requirements of a Collection, but adds additional requirements specific to that particular type of collection.

Any time it makes sense to create an inheritance hierarchy for interfaces, then you should. If two interfaces will always be found together, then they should probably be merged.

Related Topic