13

I am planning to move my system to generic service layer.

public interface IAbcService<TEntity> where TEntity : class

public class AbcService<TEntity> : IAbcService<TEntity> where TEntity : class

I tried something but it does not work.

services.AddTransient<typeof(IAbcService<MyEntity>), AbcService();
....
....
....

I'm using some of my entities and along with that I am trying to add it to properties.

How can I register a generic service in asp.net core?

phoenix
  • 3,069
  • 3
  • 22
  • 29
Generic Guy
  • 131
  • 1
  • 1
  • 3
  • If an answer met your needs, please mark it as accepted. If not, please comment on the answer or edit your question. – JonTheMon Mar 30 '16 at 13:28

2 Answers2

27

I wanted to try the exact same thing before and I've got it to work like this:

services.AddTransient(typeof(IAbcService<>), typeof(AbcService<>));
services.AddTransient(typeof(IAbcService<Person>), typeof(AbcService<Person>));

Do mind the different structure, this is registering by parameters in a method.

To elaborate, as you can see in the example above, with the new DNX framework package we now can register both open and closed generics. Try it out, both lines will work.

Sam
  • 1,634
  • 13
  • 21
  • 1
    Love the first line of code as this allowed me to register the service for all descendants of "Person" (in this case) !!! Awesome! – neggenbe Mar 29 '20 at 11:05
-7

Have you tried

services.AddTransient<IAbcService<>, AbcService>()

JonTheMon
  • 381
  • 2
  • 9
  • That won't compile. You have to use run-time `System.Type` instances via `typeof()` when referencing open generics. – Technetium Aug 29 '16 at 17:10