You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过依赖注入管理控制器泛型类型,消除冗余与类型安全问题

问题描述

我维护多个控制器,每个都必须显式指定泛型类型,这不仅造成大量代码冗余,还容易引发类型安全问题。

当前控制器实现

public class DemoController : DemoBaseController<Guid, Guid>
{
    public DemoController(IUnitOfWork<Guid, Guid> uow) : base(uow)
    {
    }
}

public class DemoPermissionController : DemoPermissionBaseController<Guid, Guid>
{
    public DemoPermissionController(IUnitOfWork<Guid, Guid> uow) : base(uow)
    {
    }

Program.cs 配置

var builder = WebApplication.CreateBuilder(args);

// 向容器添加服务
builder.Services.AddControllers();
builder.Services.AddDemoManagementDI<Guid, Guid, DemoRoleContext>();

AddDemoManagementDI 方法实现

public static void AddDemoManagementDI<TKey, TBKey, TContext>(this IServiceCollection services) 
    where TKey : IEquatable<TKey> 
    where TBKey : IEquatable<TBKey> 
    where TContext : DbContext, IDemoManagementContext<TKey, TBKey>
{
    IConfiguration configuration = services.BuildServiceProvider().GetService<IConfiguration>();
    services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
    services.AddDbContext<DbContext, TContext>(delegate (DbContextOptionsBuilder options)
    {
        options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
    });
    services.AddAuthentication(delegate (AuthenticationOptions options)
    {
        options.DefaultAuthenticateScheme = "Bearer";
        options.DefaultChallengeScheme = "Bearer";
        options.DefaultScheme = "Bearer";
    }).AddJwtBearer(delegate (JwtBearerOptions options)
    {
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateAudience = false,
            ValidateIssuer = false,
            ValidateLifetime = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Secret"])),
            ClockSkew = TimeSpan.FromMinutes(5.0)
        };
    });
    services.AddAuthorization();
    services.AddCors();
    services.AddSwaggerGen(delegate (SwaggerGenOptions c)
    {
        // 原代码此处存在语法缺失,保留结构原样
    });
    services.AddScoped<IRepositoryResponse, RepositoryResponse>();
    services.AddScoped(typeof(IDatabaseGenericRepository<,>), typeof(EntityFrameworkGenericRepository<,>));
    services.AddScoped<IDemoService<TKey, TBKey>, DemoService<TKey, TBKey>>();
    services.AddScoped<IDemoPermissionService<TKey, TBKey>, DemoPermissionService<TKey, TBKey>>();
    services.AddScoped<IUnitOfWork<TKey, TBKey>, UOWService<TKey, TBKey>>();
    services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
    services.AddScoped((IServiceProvider provider) => (IDemoManagementContext<TKey, TBKey>)provider.GetService(typeof(TContext)));
}

期望的控制器泛型实现

我希望将控制器改为以下泛型形式,以此解决代码冗余和类型安全问题:

public class RoleController<TUserKey, TAuthKey> : RoleBaseController<TUserKey, TAuthKey>
{
    public RoleController(IUnitOfWork<TUserKey, TAuthKey> uow) : base(uow)
    {
    }
}

内容的提问来源于stack exchange,提问作者Ammad Khalid Butt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 23:45:37