如何通过依赖注入管理控制器泛型类型,消除冗余与类型安全问题
问题描述
我维护多个控制器,每个都必须显式指定泛型类型,这不仅造成大量代码冗余,还容易引发类型安全问题。
当前控制器实现
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
相关产品推荐
相关产品推荐

