在.NET Core中注入通用接口 [英] Inject generic interface in .NET Core

查看:86
本文介绍了在.NET Core中注入通用接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将此接口注入我的控制器:

I want to inject this interface to my controllers:

public interface IDatabaseService<T>
    where T : class
{
    T GetItem(int id);

    IEnumerable<T> GetList();

    void Edit(T data);

    void Add(T data);

    void Remove(T data);
}

我想使用通用的,因为在我的 WebApi 项目中,我有 ProjectController TaskController 等控制器,并且我想使用通用接口到每种类型(例如, IDatabaseService< Project> IdatabaseService< Task> 等).

I want to use generic, because in my WebApi project i have controllers like ProjectController, TaskController etc and i want to use generic interface to each of type (for example, IDatabaseService<Project>, IdatabaseService<Task> etc).

将被注入控制器的类如下所示:

Class, that will be injected to controller will look like this:

public class ProjectService : IDatabaseService<Project>
{
    public ProjectService(DbContext context)
    {
        this.context = context;
    }

    private readonly DbContext context;

    public Project GetItem(int id)
    {
    }

    public IEnumerable<Project> GetList()
    {
    }

    public void Edit(Project data)
    {
    }

    public void Add(Project data)
    {
    }

    public void Remove(Project data)
    {
    }
}

但是当我尝试注入我的 Startup.cs 时:

But when i try to ineject in my Startup.cs:

services.AddScoped<IDatabaseService<T>>();

我需要传递 T 类型.

我的问题是,如何使注入通用,以及如何在控制器中正确注入?例如:

My question is, how to make injection generic and how inject it properly in controller? For example:

public class ProjectController : ControllerBase
{
    private readonly ProjectService projectService;

    public ProjectController (IDatabaseService<Project> projectService)
    {
        this.projectService = projectService;
    }
}

是否可以?将通用接口注入控制器是否是一种好习惯?如果没有,该如何做得更好?

If it will work? And is it good practice to make generic interface to inject into controllers? If no, how to do it better?

推荐答案

1.)如果要编写硬代码

1.) if you want to write hard code

services.AddScoped<IDatabaseService<Project>, ProjectService>();

2.)如果要动态注册所有已实现的 IDatabaseService<>

2.) if you want to register dynamically that all types of implemented IDatabaseService<>

        System.Reflection.Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(item => item.GetInterfaces()
            .Where(i => i.IsGenericType).Any(i => i.GetGenericTypeDefinition() == typeof(IDatabaseService<>)) && !item.IsAbstract && !item.IsInterface)
            .ToList()
            .ForEach(assignedTypes =>
            {
                var serviceType = assignedTypes.GetInterfaces().First(i => i.GetGenericTypeDefinition() == typeof(IDatabaseService<>));
                services.AddScoped(serviceType, assignedTypes);
            });

这篇关于在.NET Core中注入通用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆