karaxuna
karaxuna

Reputation: 26930

Generic Controllers

I have multiple controllers that have some common actions. I have made generic controllers:

 public class FirstBaseController<TEntity> where TEntity : class, IFirst, new()
 public class SecondBaseController<TEntity> where TEntity : class, ISecond, new()

Then i want to do something like this:

 public class MyController : FirstBaseController<First>, SecondBaseController<Second>

And I know that multiple class inheritance is not allowed in C#. Can you tell me alternative way to do this?

Upvotes: 1

Views: 198

Answers (1)

jeroenh
jeroenh

Reputation: 26782

The only option is to replace the base classes by interfaces and achieve reuse through composition:

public interface IMyFirstSetOfMethods<TEntity> { /*... */ }
public interface IMySecondSetOfMethods<TEntity> { /*... */}

public class FirstImpl 
{

}

public class SecondImpl
{
}


public class MyController : IMyFirstSetOfMethods<First> , IMySecondSetOfMethods<Second>
{
    FirstImpl myFirstImpl = new FirstImpl();
    SecondImpl mySecondImpl = new SecondImpl();

    // ... implement the methods from the interfaces by simply forwarding to the Impl classes
}

Upvotes: 2

Related Questions