简体   繁体   中英

How to manage and control generics types to provide in Controller classes, using Dependency Injection or something

I have multiple controllers and in all of them I need to provide generic types. This causes sort of redundancy as well as issues with type safety

Here are my Controllers

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 file

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddDemoManagementDI<Guid, Guid, DemoRoleContext>();

In 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)));
    }

I actually want it to be something like this.

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

Build in DI container allows to register open generic types, ie the only one following registration:

services.AddScoped(typeof(IUnitOfWork<,>), typeof(UOWService<,>));

will allow next class:

class SomeController<TUserKey, TAuthKey>
{
    private readonly IUnitOfWork<TUserKey, TAuthKey> _uow;

    public SomeController(IUnitOfWork<TUserKey, TAuthKey> uow)
    {
        _uow = uow;
    }
}

Be successfully resolved with all generic type parameters provided:

IServiceProvider sp = app.Services;
using (var scope = sp.CreateScope())
{
    var someController = scope.ServiceProvider.GetRequiredService<SomeController<Guid, Guid>>();
}

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