autofac单例初始化

时间:2017-07-17 18:19:44

标签: c# singleton autofac lifetime-scoping

我有一个像这样的接口和类:

public sealed class UserService : IUserService
{
    private readonly ILifetimeScope container;
    public UserService()
    {
        this.container = this.ConfigureBuilder(new ContainerBuilder()).Build();
    }

    private ContainerBuilder ConfigureBuilder(ContainerBuilder builder)
    {
        builder.RegisterType<UserConfiguration>()
            .AsImplementedInterfaces();
        builder.Register(c => this.GetCredentialHelperAsync(c))
            .As<ICredentialProvider>()
            .SingleInstance();
        return builder;
    }

    private async Task<CredentialProvider> GetCredentialHelperAsync(IComponentContext componentContext)
    {
       //This seems to causing problem as I think I cannot access component when I am build. 
        var config = componentContext.Resolve<UserConfiguration>();
        if (config.User == null)
        {
            //ADD the user and set credentials
        }
        var userCredentials = new List<IUserCredential>();
        return new UserCredentialProvider(userCredentials)
    }
}

当我使用autofac并且我想将此类注册为singleton时,我该怎么做。问题是在运行时从文件读取凭据后确定用户凭据的值。

使用上面的代码我正在构建UserCredentialProvider的异常,因为我认为在构建期间我们无法访问对象。有出路吗?

0 个答案:

没有答案