How do I Register Open Generics in ServiceCollection when they aren't "equal"

5 days ago 8
ARTICLE AD BOX

I have an open generic registration that works fine

services.AddScoped(typeof(IAsyncRepository<>), typeof(AsyncRepository<>));

My point is that I have this other case

public interface IAsyncEvent<in TEvent> where TEvent : class { Task HandleAsync(TEvent eventArg, CancellationToken ct); } public class CreateAction<TModel>(TModel model) : ICloneable where TModel : class { public TModel Model { get; } = model; } public class CreateEventAsync<TModel>(IAsyncRepository<TModel> repository) : IAsyncEvent<CreateAction<TModel>> where TModel : class { public async Task HandleAsync(CreateAction<TModel> eventArg, CancellationToken ct) { await repository.CreateAsync(eventArg.Model, userContext, ct); } }

and what I wanted was to register the open generic type and resolve it

services.AddScoped( typeof(IAsyncEvent<>).MakeGenericType(typeof(CreateAction<>)), typeof(CreateEventAsync<>) );

this code doesn't run at all

services.AddScoped( typeof(IAsyncEvent<CreateAction<>>)), typeof(CreateEventAsync<>) );

this one doesn't compile

The other option with a function could work, but I needed more parameters, for example receive the type that was requested, the closed generic one

Or one alternative would be to have a scoped that instead of returning the factory would return the type to be constructed instead.

It could be transient in this case also

Read Entire Article