简体   繁体   中英

Generic controller class with inheritance .NET

I am making a custom controller class, from which all my other controller classes will inherit in.Net Framework 4.8, Web API

public class BaseApiController<T> where T: class, ApiController
{
    protected T service;

    public BaseApiController(T service)
    {
        this.service = service;
    }
}

This gives a compile-time error

Error CS0450 'ApiController': cannot specify both a constraint class and the 'class' or 'struct' constraint

I know I am missing small detail with the right syntax.
T is a service, which is individual for every controller and I want to make sure it is always a reference type. I also want to inherit from the main ApiController class.

If I do it like this, there are no errors (This works for me):

public class BaseApiController<T> : ApiController
{
    protected T service;

    public BaseApiController(T service)
    {
        this.service = service;
    }
}

But I want the additional T logic for reference type.

I want to use it like this, eg:
Note: This how I use it and it works.

[Authorize]
[RoutePrefix("api/[controller]")]
public class MyOtherController : BaseApiController<IMyOtherService>
{
    public MyOtherController(IMyOtherService myOtherService) : base(myOtherService)
    {

    }

    [HttpPost]
    public IHttpActionResult DoSomething(Model requestModel)
    {
        var result = this.service.SetPaymentStatusUK(model: requestModel);
        return Ok();
    }
}

I just want to know how to add the T check for reference type in the BaseApiController class.

If I understand your question right, the issue is that you applied ApiControler as a Constraint to T. When you wanted to apply it as a Ancestor of BaseApiController<T> .

As a constraint ApiControler it is not valid, because you already applied the class constraint. class include all classes, including ApiControler and every other class that has yet to be written. It is a less restrictive constraint the ApiControler. You only use a specific type or inferface as constraint, if you want all possible T's the absolutely positively have that inheritance/Interface Implementation.

According to the Syntax examples , you first inherit, then you constrain. So:

public class BaseApiController<T> : ApiController where T: class
{
  //all the code
}

Might be the droid you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM