2

I do have added some services to the startup method on Startup.cs.

This service is a Generic service for a specific Type. Here is my startup code:

services.AddTransient<BaseEntityService<Subscription>>();
services.AddTransient<BaseEntityService<Customer>>();
services.AddTransient<BaseEntityService<Asset>>();
services.AddTransient<BaseEntityService<Product>>();
// ...

O my Controller I require the service like:

public MyAssetController(BaseEntityService<Asset> service){ //...

Is there a way to do not repeat the generic service to every class type on the startup? just add a generic type? like this:

services.AddTransient<BaseEntityService>(); // Doesn't works..
Daniel Santos
  • 14,328
  • 21
  • 91
  • 174
  • I would just take the generic type parameter off the class and put it on the methods, then you don't need to do this. – mcintyre321 Mar 08 '18 at 14:16

1 Answers1

3

Try this

services.AddTransient(typeof(BaseEntityService<>));

Something similar was mentioned here: Generic repository in ASP.NET Core without having a separate AddScoped line per table in Startup.cs?

EDIT: Removed the first parameter as the type was the same.

KingChezzy
  • 136
  • 7
  • Please kindly do not post other SO answer. Instead, please close it as duplicate. – Win Mar 08 '18 at 14:18
  • How do I do that? Sorry new here. – KingChezzy Mar 08 '18 at 14:20
  • Click on close link at the bottom of the question. [Here](https://i.stack.imgur.com/uLWm1.png) is the screen shot. – Win Mar 08 '18 at 14:22
  • 1
    Sorry but I need 3000 rep for that option. – KingChezzy Mar 08 '18 at 14:24
  • There is a difference about what you mentioned and the other question.. The question does mention 'AddScoped' and here you mentioned 'AddTransient' . Is that correct? – Daniel Santos Mar 08 '18 at 14:25
  • 1
    Transient classes are created every time they are requested. Scoped is once per request. Singleton is lifetime (but created on their first time being requested) Info here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection#service-lifetimes-and-registration-options – KingChezzy Mar 08 '18 at 14:27