使用 dotnet core 3 注册 Open Generic [英] Register Open Generic with dotnet core 3

查看:19
本文介绍了使用 dotnet core 3 注册 Open Generic的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的应用程序中注册一个 Open Generic 类型,但我有一个奇怪的行为.

I'm trying to register an Open Generic type in my application but I'm having a strange behavior.

以下工作正常:

services.AddTransient(typeof(IA<>), typeof(A<>));

现在,我想将参数传递给我的 A 类,因为我的构造函数有一些参数:

Now, I would like to pass parameters to my A class, because my constructor has some arguments:

services.AddTransient(typeof(IA<>), provider =>
{
    return ActivatorUtilities.CreateInstance(provider, typeof(A<>), "1", "2");
});

这会产生一个异常

'打开通用服务类型'IA`1[T]'需要注册一个开放的通用实现类型.(范围'描述符')'

'Open generic service type 'IA`1[T]' requires registering an open generic implementation type. (Parameter 'descriptors')'

好的,所以我简化了我的工厂,只是做了这样的事情:

Ok so I simplified my factory, and just did something like this:

services.AddTransient(typeof(IA<>), provider => typeof(A<>));

但这会产生完全相同的异常.

But this generates exactly the same exception.

问题很简单:如何使用默认的 .net core DI 注册带有参数的 Open Generic?(我不想使用像Castle Windsor这样的第三方库)

Question is simple: How to register an Open Generic with parameters with the default .net core DI ? (I don't want to use a third party library like Castle Windsor)

注意A<>的构造函数有可选参数,这就是为什么services.AddTransient(typeof(IA<>), typeof(A<>)); 正在工作

Note that the constructor of A<> has optional parameter, this is why services.AddTransient(typeof(IA<>), typeof(A<>)); is working

推荐答案

可以将A<>参数的构造函数包裹到一个类中并注入,而不是传递参数

You can wrap the constructor of A<> parameters into a class and inject it instead of passing the parameters

services.AddTransient(typeof(IA<>), typeof(A<>));
services.AddTransient<AOptions>(sp => new AOptions { X = "1", Y = "2" });

public class A<T> : IA<T>
{
    private readonly AOptions _aOptions;

    public A(AOptions aOptions = null)
    {
        _aOptions = aOptions;
    }
}

public class AOptions
{
    public string X { get; set; }
    public string Y { get; set; }
}

这篇关于使用 dotnet core 3 注册 Open Generic的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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