我有一个类A,它必须是singleton,并且在创建async Initialization方法时必须调用它.我在DryIoc文档中没有找到合适的功能.在我看来,RegisterDelegate方法是最接近的,但它不接受异步lambda作为参数.

为了清楚起见,我将举一个例子摆在你们面前:

public class A
{
    ...
    public async Task<A> Initialization() {...}
    ...
}

var instance = await new A().Initialization();

推荐答案

答案1

由于two-colored function problem及其相关的复杂性,DryIoc尚不支持async初始化.

基本上,我需要介绍为整个依赖关系链生成的单独的await调用图,其中一些是从ResolveAsync或类似的API开始的async.

如果没有,您可以使用第https://endjin.com/blog/2023/01/dotnet-csharp-lazy-async-initialization条末尾讨论的方法.

在这种方法中,您将把初始化的等待部分从构造阶段移到方法中(S).

因此,您可以将异步初始化作为Func依赖项添加到构造函数中:

public class A
{
    readonly Task _finishInitAsync;
    
    // Actually kicking off the initialization part in the constructor to start the job,
    // but postpone the await of the already finished or in-progress initialization until the first using method.
    // Alternatively, you may use Lazy<Func<A, Task>> parameter instead to postpone the whole initialization until the using method call.
    public A(Func<A, Task> initAsync) => _finishInitAsync = initAsync(this); 
    
    // Making it static to detach from the A and simplify the passing it around
    public static async Task Initialization(A a) {...}
    ...
    public async Task MethodUsingTheInit() 
    {
       await _finishInitAsync();
       // do stuff
    }

}

container.Register<A>();
container.RegisterDelegate<Func<A, Task>>(_ => a => A.Initialization(a));

var a = container.Resolve<A>();
await a.MethodUsingTheInit();

答案2

你可以进入全手动模式,这在我看来要简单得多. 在第一次使用前手动拨打Initialization.

// `New` allows to construct the A by injecting its dependencies from the container,
// but without actually registering the A itself.
var a = container.New<A>();

await A.Initialization(a);

// Then register the fully initialized A into container
container.RegisteInstance(a);

反馈

我对这一主题以及替代解决方案的任何 idea 都非常感兴趣.

Csharp相关问答推荐

如何从顶部提取发票号作为单词发票后的第一个匹配

找不到网址:https://localhost:7002/Category/Add?区域= Admin.为什么我的URL是这样生成的?area = Admin而不是/Admin/

如何在C#中将对象[*,*]直接转换为字符串[*,*]?

此反射有什么问题.是否发送值转换委托?

如何注册接口类型,类型<>

使页面内容居中

Azure Redis缓存与Entra ID身份验证

.NET 6控制台应用程序,RabbitMQ消费不工作时,它的程序文件中的S

用C#调用由缓冲区指针参数组成的C API

如何在C#中从正则表达式中匹配一些数字但排除一些常量(也是数字)

WeakReference未被垃圾收集

C#普罗米修斯指标

如何在我的C#应用程序中设置带有reactjs前端的SignalR服务器?

C#多键字典和TryGetValue

读取测试项目中的应用程序设置

单位中快照的倾斜方向

将两个JSON文件与覆盖值的主文件合并

从具有泛型类型约束的类继承-Blazor

MudRadioGroup不切换

阻止CLR释放已封送的双字符指针的内存?