Josbel Luna
Josbel Luna

Reputation: 2824

Get the Generic Type in Dependency Injection Asp Net Core

I Want to archive a global solution to all of my generic services, I Have the following code:

services.AddScoped(typeof(IService<>), provider => ResolveService(genericType));

I need one parameter that is the generic type needed to resolve the service and return the right instance.

There is a way to extract the Generic type needed by the interface in this case?

Upvotes: 0

Views: 496

Answers (1)

Timur Lemeshko
Timur Lemeshko

Reputation: 2879

I think, you should use service resolver in your classes then. But you should know - this is an anti-pattern

public interface IService<T>
    {

    }

    public interface IResolveService
    {
        IService<T> Resolve<T>();
    }

    public class ResolveService : IResolveService
    {
        private readonly IServiceProvider _provider;

        public ResolveService(IServiceProvider provider)
        {
            _provider = provider;
        }

        public IService<T> Resolve<T>()
        {
            //some logic here. May by resolving some instances using IServiceProvider
            throw new NotImplementedException();
        }
    }

    public class MyClass
    {
        public MyClass(IResolveService resolveService)
        {
            Service = resolveService.Resolve<int>();
        }

        private IService<int> Service { get; }
    }

Upvotes: 1

Related Questions