当您从另一个sup类的子类调用方法时,如何从超类的子类执行方法?

问题描述 投票:0回答:1

我目前正在使用ASP Net Core构建Rest API。我正在阅读Medium中的本教程,该教程是有关存储库模式实现的教程。这是Link

我有2个超类,每个超类都有一个子类。我有超类TController和TService以及子类UserController和UserService。我想从UserController调用UserService的方法。该方法在UserService中定义,但不在TService的超类中定义。

所以我的问题是:当您从UserController调用它时,如何执行在UserController中设置的方法?] >>

这里是控制器:

public abstract class TController<TEntity, TService> : ControllerBase
    where TEntity : class, IEntity
    where TService : IService<TEntity>
{

    private TService service;

    public TController(TService service)
    {
        this.service = service;
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<TEntity>>> Get()
    {
        return await this.service.GetAll();
    }

    [Methods GetId, Add, Update, Delete, but cut out to keep the code short]

}

public class UserController : TController<UserModel, UserService>
{
    public UserController(UserService service): base(service)
    {
    }

    [HttpGet("/check")]
    public bool Check()
    {


        return base.CheckPassword("Bollox")
    }

}

这里是服务:

 public interface IService<T> where T: class, IEntity
{
    Task<List<T>> GetAll();
    [Methods GetId, Add, Update, Delete, but cut out to keep the code short]
}

public abstract class TService<TEntity, TRepository>: IService<TEntity>
    where TEntity: class, IEntity
    where TRepository: IRepository<TEntity>
{
    private TRepository repository;

    public TService(TRepository repository)
    {
        this.repository = repository;
    }

    public async Task<List<TEntity>> GetAll()
    {
        return await this.repository.GetAll();
    }


}

public class UserService : TService<UserModel, UserRepository>
{
    public UserService(UserRepository repository) : base(repository)
    {

    }

    public bool CheckPassword(String password)
    {

        return true;

    }

}

我尝试两次定义UserService,这行得通,但是还有更好的方法吗?

 public class UserController : TController<UserModel, UserService>
{
    private readonly UserService svc;

    public UserController(UserService service): base(service)
    {
        this.svc = service;
    }

    [HttpGet("/check")]
    public bool Check()
    {


        return svc.CheckPassword(new UserModel
        {
        });
    }

}

我目前正在使用ASP Net Core构建Rest API。我正在阅读Medium中的本教程,该教程是有关存储库模式实现的教程。链接在这里。我有2个超类,...

c# superclass
1个回答
2
投票

您可以选择只在基类中保护service-当您使用泛型时,您仍然可以访问所有UserService

public abstract class TController<TEntity, TService> : ControllerBase
    where TEntity : class, IEntity
    where TService : IService<TEntity>
{

    protected readonly TService service;

    public TController(TService service)
    {
        this.service = service;
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<TEntity>>> Get()
    {
        return await this.service.GetAll();
    }

    [Methods GetId, Add, Update, Delete, but cut out to keep the code short]

}
© www.soinside.com 2019 - 2024. All rights reserved.