在Autofac注册异步厂 [英] Registering async factory in Autofac

查看:478
本文介绍了在Autofac注册异步厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个钱包类,我从一个存储库中获得。我想在Autofac正确注册都因此使用电子钱包类可以有注入适当的实例。问题是,该信息库采用异步方法(返回的任务)。 ?是否Autofac支持这样的情况下

I have a Wallet class that I get from a repository. I'm trying to properly register both in Autofac so classes using the wallet could have a proper instance injected. The problem is that the repository uses an async method (returning Task). Does Autofac support such cases?

这不工作:

This doesn't work:

cb.RegisterType<WalletRepository>()
    .As<IWalletRepository>()
    .SingleInstance();
cb.Register(async c => await c.Resolve<IWalletRepository>().CreateAsync(App.WalletPath));
cb.RegisterType<ViewModel>()
    .AsSelf().
    .SingleInstance();



某处的应用程序,我只是有:

Somewhere in the app I just have:

class ViewModel
{
    public ViewModel(Wallet wallet)
    {
        //nothing fancy here
    }
}

当调用 container.Resolve<视图模型>()我得到一个异常说钱包没有注册。

When calling container.Resolve<ViewModel>() i get an exception saying Wallet is not registered.

推荐答案

除非我记错Autofac没有任何异步工厂为的具体支持。您仍然可以使其工作,但你必须写一些样板代码,因为构造器注入将无法工作。你还必须更文字,说你要任务< T> 而不是 T 。整个代码看起来是这样的:

Unless I'm mistaken Autofac doesn't have any specific support for async factories. You can still make it work, but you have to write some boilerplate code, because constructor injection won't work. You also have to be more literal and say you want Task<T> instead of T. The whole code would look something like this:

cb.RegisterType<WalletRepository>()
  .As<IWalletRepository>()
  .SingleInstance();
cb.Register(c => c.Resolve<IWalletRepository>().CreateAsync(App.WalletPath));
cb.Register(async c => new ViewModel(await c.Resolve<Task<Wallet>>()))
  .SingleInstance();
var container = cb.Build();
var viewModel = await container.Resolve<Task<ViewModel>>();



这是可能的Autofac具有一定的扩展点,使这个代码更简单,但我不知道有足够的了解它帮你。

It's possible Autofac has some extensibility points to make this code simpler, but I don't know enough about it to help you with that.

这篇关于在Autofac注册异步厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆