使用异步 InjectionFactory
Use an async InjectionFactory
我会在 Unity 注入工厂中调用异步函数,就像这样...
Container.RegisterType<HttpClient>(new InjectionFactory(
async c => await Create()));
...但是它说...
Error CS4010: Cannot convert async lambda expression to delegate type
'Func'. An async lambda expression may return
void, Task or Task, none of which are convertible to
'Func'.
有解决办法吗?
使用 DelegateInjectionFactory
将工厂注册为 Task<HttpClient>
。然后你可以 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();
}
接受注射的 class 示例:
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.whosebug.com");
var text = await result.Content.ReadAsStringAsync();
return text;
}
}
现在 Create()
将异步执行,但容器不会等待(容器未为此设置)。相反,它由您自己的代码等待,在使用它的 class 中,您可以控制它。
注意:虽然此示例表明它是 可能的 ,但我可能不会在生产代码中这样做。更常见的是写一个工厂class,给它一个async方法,注入工厂class,等待class中的方法接收注入。
我会在 Unity 注入工厂中调用异步函数,就像这样...
Container.RegisterType<HttpClient>(new InjectionFactory(
async c => await Create()));
...但是它说...
Error CS4010: Cannot convert async lambda expression to delegate type 'Func'. An async lambda expression may return void, Task or Task, none of which are convertible to 'Func'.
有解决办法吗?
使用 DelegateInjectionFactory
将工厂注册为 Task<HttpClient>
。然后你可以 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();
}
接受注射的 class 示例:
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.whosebug.com");
var text = await result.Content.ReadAsStringAsync();
return text;
}
}
现在 Create()
将异步执行,但容器不会等待(容器未为此设置)。相反,它由您自己的代码等待,在使用它的 class 中,您可以控制它。
注意:虽然此示例表明它是 可能的 ,但我可能不会在生产代码中这样做。更常见的是写一个工厂class,给它一个async方法,注入工厂class,等待class中的方法接收注入。