答案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 都非常感兴趣.