Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register generic service [duplicate]

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?

like image 363
Generic Guy Avatar asked Feb 05 '16 19:02

Generic Guy


1 Answers

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.

like image 139
Sam Avatar answered Oct 31 '22 15:10

Sam