1

I'm going to create hundreds of classes. If they all implemented the same class, do I have to register them one by one?

Example

public class Service<TEntity>: IService<TEntity> {...}

public Interface IService<TEntity> where TEntity : class {...}

public class class1 : Service<apple>, IClass1 {...}

public class class234 : Service<orange>, IClass234 {...}

In my controller I would like to inject it like this

public class FoodController : Controller{
     private IClass1 _class1;
     private IClass234 _class234;

     FoodController(IClass1 ic1, IClass234 ic234){
          _class1 = ic1;
          _class234 = ic234;
     }
}

I've done this before with Unity in older versions of ASP.NET How can I do this with the built in DI of ASP.NET CORE 2.0?

In the controller, I can inject the specific interface of IClass1 and IClass234 in the constructor. This is what I'm trying to achieve because I would also like to use the other methods from the other interfaces that the classes implement.

public void ConfigureServices(IServiceCollection services)
{
    // Is there a way to register all 234 classes without typing out services.addTransient...
}
6
  • medium.com/agilix/… Commented Mar 30, 2019 at 4:26
  • @JohanP I've already gone through that. That's not what I'm looking for. I want to inject each service separately in the controller because they will also have class specific functionality. Commented Mar 30, 2019 at 4:30
  • If you have multiple implementations of the same interface, then it will inject an IEnumerable<T> Commented Mar 30, 2019 at 4:32
  • @JohanP I would have to iterate through IEnumerable or select the instance I want with linq. How is that related to what I'm asking for? Commented Mar 30, 2019 at 4:36
  • Is your question not // Is there a way to register all 234 classes without typing out services.addTransient...? If it is, then the link I provided and you have already seen answers your question. If your question is what your title is, then I have already answered it above, it will inject an IEnumerable<T> then you will have to use linq to find it. If that is not your question, maybe make it clearer. Commented Mar 30, 2019 at 4:43

1 Answer 1

1

With the standard DI container you do have to register one by one.

But you can use another library to register it automatically by naming convention:

https://www.google.com/amp/s/andrewlock.net/using-scrutor-to-automatically-register-your-services-with-the-asp-net-core-di-container/amp/

Sign up to request clarification or add additional context in comments.

Comments

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.