Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to call To(factory) with an async method #62

Unanswered
alex6dj asked this question in Q&A
Discussion options

The title has the question. So I want to initialize TelegramUserBot during injection but .Initialize() is an async method and factory dont accept a Task<> return.

IConfiguration To<T>(global::System.Func<IContext, T> factory);

image

Any solution ? Thanks.

You must be logged in to vote

Replies: 2 comments 1 reply

Comment options

It seems that what I thought was wrong. What would be the correct way to initialize this class would be the correct question.

You must be logged in to vote
0 replies
Comment options

@alex6dj Unfortunately for factories you can't use the syntax with the "async" keyword right now. But you can do it like this:

using Pure.DI;
var composition = new Composition();
var consumer = composition.Consumer;
await consumer.RunAsync();
DI.Setup(nameof(Composition))
 .Bind().To(ctx =>
 {
 ctx.Inject(out Bot bot);
 // Returns Task<Bot>
 return bot.InitializeAsync()
 .ContinueWith(_ => bot);
 })
 .Root<Consumer>("Consumer");
class Bot
{
 public async Task InitializeAsync()
 {
 Console.WriteLine("Initialize");
 await Task.Delay(3000);
 Console.WriteLine("Initialized");
 }
 public void DoSomethig() => 
 Console.WriteLine("Done");
}
class Consumer(Task<Bot> botTask)
{
 public async Task RunAsync()
 {
 Console.WriteLine("Start");
 var bot = await botTask;
 bot.DoSomethig();
 Console.WriteLine("Finish");
 }
}

I'll think about a solution to this issue, but I'm not sure it can be done easily yet.

You must be logged in to vote
1 reply
Comment options

@NikolayPianikov thanks for the fast answer. Im using this DI library for NativeAOT publication.
Im using Rx.Net in my apps and doing for now a similar workaround for the initialization step and its working ok.

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /