如何注册接口<type, type>

问题描述 投票:0回答:1

我正在尝试在我的 .Net 8 应用程序中设置依赖项注入,并希望它根据命名约定进行扫描和注册。我陷入困境的是我不知道如何注册

IFoo<in T1, out T2>
,有人创建了它的实现来设置对象的自定义映射。具体实现继承自
IFoo
的接口。

这是迄今为止我的 DI 代码:

public static void ConfigureServices(IServiceCollection services, Assembly assembly)
{
    var types = assembly.GetTypes()
        .Where(t => t.GetInterfaces().Any(i => i.IsGenericType)).ToList();

    foreach (var type in types)
    {
        var interfaces = type.GetInterfaces();

        foreach (var @interface in interfaces)
        {
            // Register the interface mapping to the type in DI container
            services.AddTransient(@interface, type);

            // Register a factory for the Funcs
            services.AddTransient(typeof(Func<>).MakeGenericType(@interface),
                provider => new Func<object>(() => provider.GetService(@interface)));
        }
    }
}

以下是如何设置课程的示例:

 public interface ISpecificFoo : IFoo<Member, SpecificFoo.Output>
 {
 }

 public class SpecificFoo : ISpecificFoo 
 {
     public class Output
     {
     }
 }

到目前为止我遇到的错误是:

System.ArgumentException:'无法实例化实现类型 'ISpecificFoo' 对于服务类型 'IFoo`2

c# .net-core dependency-injection
1个回答
2
投票

您没有过滤掉接口类型,因此如果您有任何扩展

IFoo<in T1, out T2>
的接口(如
ISpecificFoo
所做的那样),那么它将被错误地注册为实现类型。

你可以这样做:

var types = assembly
    .GetTypes()
    .Where(t => !t.IsAbstract) // Don't consider interfaces (or abstract classes).
    .Where(t => t.GetInterfaces().Any(i => i.IsGenericType))
    .ToList();

现在只有可实例化的类型才会被注册,例如

SpecificFoo

为了进一步限制这一点,您可以专门将

IFoo<in T1, out T2>
作为服务类型:

var interfaces = type
    .GetInterfaces()
    .Where(i =>
        i.IsGenericType &&
        i.GetGenericTypeDefinition() == typeof(IFoo<,>));
© www.soinside.com 2019 - 2024. All rights reserved.