使用异步InjectionFactory

时间:2018-07-13 23:12:44

标签: c# async-await unity-container

我会在Unity注入工厂中调用异步函数,就像这样...

Container.RegisterType<HttpClient>(new InjectionFactory(
                async c => await Create()));

...但是它说...

  

错误CS4010:无法将异步Lambda表达式转换为委托类型   'Func'。异步lambda表达式可能返回   无效,任务或任务,都不能转换为   “功能”。

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:1)

使用Task<HttpClient>将工厂注册为DelegateInjectionFactory。然后,可以在您控制的代码中await对其进行public static IUnityContainer CompositionRoot() { var container = new Unity.UnityContainer(); container.RegisterType<Application>(); container.RegisterType<Task<HttpClient>> ( new DelegateInjectionFactory ( new Func<Task<HttpClient>> ( async () => await Create() ) ) ); return container; } public static async Task<HttpClient> Create() { await Task.Delay(1); //Simulate doing something asynchronous return new HttpClient(); }

public class Example
{
    protected readonly Task<HttpClient> _client; //Injected

    public Example(Task<HttpClient> client)
    {
        _client = client;
    }
    public async Task<string> Run()
    {
        var result = await (await _client).GetAsync("http://www.StackOverflow.com");
        var text = await result.Content.ReadAsStringAsync();
        return text;
    }
}

将接受注射的类的示例:

Create()

现在for row in range(0, size[0]): for col in range(0, size[1]): if ind >= text_length : break # only change pixel value for length of text r = convert_char_to_int(text[ind], limit=limit) ind = max( ind+1, text_length - 1) # don't go beyond text length g = convert_char_to_int(text[ind], limit=limit) ind = max( ind+1, text_length - 1) b = convert_char_to_int(text[ind], limit=limit) ind += 1 img.putpixel((row, col), (r,g,b)) 将异步执行,但不会被容器等待(尚未为此设置)。相反,在使用它的类中,您可以控制自己的代码来等待它。

注意:虽然此示例说明了它是可能,但我可能不会在生产代码中这样做。更常见的是编写一个工厂类,给它一个异步方法,注入工厂类,然后在接收注入的类中等待该方法。