2016-02-05 47 views
5

我打算将我的系统移至通用服务层。如何注册通用服务

public interface IAbcService<TEntity> where TEntity : class 

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

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

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

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

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

+0

如果答案满足您的需求,请将其标记为已接受。如果没有,请评论答案或编辑您的问题。 – JonTheMon

回答

-2

你试过

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

+0

这将不会编译。在引用开放泛型时,您必须通过'typeof()'使用运行时'System.Type'实例。 – Technetium

7

我想之前尝试同样的事情,我已经得到它像这样工作:

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

不要介意不同的结构,这是通过参数在方法中注册。

详细说明,如上例所示,使用新的DNX框架包,我们现在可以注册开放式和封闭式泛型。 试一下,两条线都可以工作。