0

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?

1 Answer 1

1

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; }
    }
Sign up to request clarification or add additional context in comments.

3 Comments

I think I'd have to implement a different technique to archive this.
please, write the answer if u will)
No, just for my purpose I've to change this injection by another general purpose solution, like create a generic class and by constructor resolve the behaviour of the class based on the generic type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.