How to register generic service [duplicate]

2019-04-26 19:30发布

This question already has an answer here:

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?

2条回答
来,给爷笑一个
2楼-- · 2019-04-26 20:12

Have you tried

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

查看更多
\"骚年 ilove
3楼-- · 2019-04-26 20:16

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.

查看更多
登录 后发表回答