如何注册通用服务

Gen*_*Guy 8 c# asp.net generics dependency-injection asp.net-core

我打算将我的系统移动到通用服务层.

public interface IAbcService<TEntity> where TEntity : class

public class AbcService<TEntity> : IAbcService<TEntity> where TEntity : class
Run Code Online (Sandbox Code Playgroud)

我尝试了一些东西,但它不起作用.

services.AddTransient<typeof(IAbcService<MyEntity>), AbcService();
....
....
....
Run Code Online (Sandbox Code Playgroud)

我正在使用我的一些实体,并且我正在尝试将其添加到属性中.

如何在asp.net核心中注册通用服务?

Sam*_*Sam 15

我之前想尝试完全相同的东西,我已经让它像这样工作:

services.AddTransient(typeof(IAbcService<>), typeof(AbcService<>));
services.AddTransient(typeof(IAbcService<Person>), typeof(AbcService<Person>));
Run Code Online (Sandbox Code Playgroud)

请注意不同的结构,这是通过方法中的参数进行注册.

如上所示,使用新的DNX框架包,我们现在可以注册开放和封闭的泛型.尝试一下,这两行都行.


Jon*_*Mon -7

你有没有尝试过

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