Skip to content

Using DI to determine the provider when using the constructor #5556

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
JensMagnus opened this issue Nov 10, 2020 · 0 comments
Closed

Using DI to determine the provider when using the constructor #5556

JensMagnus opened this issue Nov 10, 2020 · 0 comments
Labels

Comments

@JensMagnus
Copy link

I'm trying to find a good way of doing this. Rather than typing a whole lot, let me demonstrate what I'm trying to accomplish.

Goal

    public class MyService<IMyProviderInterface> 
    {
        private readonly IMyProviderInterface _provider;
        public MyService(IMyProviderInterface provider) 
        {
          _provider = provider;
        }

        public IAsynEnumerable<SomeDTO> GiveMeSomething
        {
           return _myprovider.INeedSomething();
        }

        public async Task<int> GenericCommonMethodInThisService() 
        {
             return 1+1;
        }
    }

Then when I want to use this service I will inject it into another service specifying which "provider" to use:

    public class SomeOtherClass 
    {
         public SomeOtherClass (MyService<ConcreteImplOfMyInterface1> myService1) 
         {
             // assignment to private readonly
         }
    }

And even allowing me to inject multiple instances

     public class SomeOtherClass 
        {
             public SomeOtherClass (MyService<ConcreteImplOfMyInterface1> myService1, MyService<ConcreteImplOfMyInterface2> myService2) 
             {
                 // assignment to private readonly
             }
        }

#1 Attempt

    public class SomeService<T> where T : IMyProviderInterface, new()
    {
        public IAsynEnumerable<SomeDTO> GiveMeSomething() 
        {
        	var instance = new T();
        		
        	await foreach(var item in instance.GiveMeSomething()) { // .... }
        }
    }

which would be used as var service = new SomeService<ConcreteImplOfMyInterface1>(); and is working fine. However I really don't like making the "instance" every time my method is called.

Is there perhaps another way of getting this done?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants