我有一个这样的接口和类:
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 并且我想将此类注册为单例时,我该怎么做。问题是用户凭据的值是在运行时从文件中读取凭据后确定的。
使用上面的代码,我在构建 UserCredentialProvider 时遇到异常,因为我认为我们在构建期间无法访问对象。有出路吗?