本文介绍了向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");
});

这会产生异常

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

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核心DI注册带有参数的Open Generic?(我不想使用温莎城堡之类的第三方库)

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 23:07