有IDbConnection注册为per-request和ApplicationOAuthProvider注册为 的连接依赖项single instance。
builder.Register(c => new SqlConnection(WebConfigUtils.DefaultConnectionString))
.As<IDbConnection>()
.InstancePerRequest();
builder.RegisterType<ApplicationOAuthProvider>()
.As<IOAuthAuthorizationServerProvider>()
.PropertiesAutowired()
.SingleInstance();
需要在身份声明中存储用户权限。为此,我创建了命令 GetRolePermissions,在此命令中我想注入IDbConnection实例。
public class GetRolePermissions
{
public class Command: IRequest<List<string>>
{
public ICollection<AspNetUserRole> UserRoles { get; set; }
}
public class Handler : AsyncRequestHandler<Command, List<string>>
{
private IDbConnection databaseConnection;
public Handler(IDbConnection databaseConnection)
{
this.databaseConnection = databaseConnection;
}
}
}
正在创建此命令 ApplicationOAuthProvider
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
private async Task<ClaimsIdentity> GenerateUserIdentityAsync(AspNetUser user, string authenticationType)
{
user.SecurityStamp = Guid.NewGuid().ToString();
var identity = await mediator.Send(new GenerateUserIdentity.Command
{
AuthenticationType = authenticationType,
User = user
});
}
}
permissions = await mediator.Send(new GetRolePermissions.Command { UserRoles = user.Roles });-GetRolePermissions.Handler需要注入时抛出错误IDbConnection,但当前的 autofac 范围ApplicationOAuthProvider是"root"并且没有iDbConnection在此范围内注册。但它存在于per-request范围内。
不想perLifettime用于 IDbConnection,因为我认为,dbConnection在不必要时应该关闭它。我想这样做:
using(var scope = AutofacConfig.container.BeginLifiTime("AutofacWebRequest"))
{
permissions = await mediator.Send(new GetRolePermissions.Command { UserRoles = user.Roles });
}
但无法使此解决方案起作用。而且我不知道如何正确获取容器,现在它是我手动设置的 AutofacConfig 的静态变量。
如何启用的注入IDbConnection到这个GetPermissions.Handler?
慕婉清6462132
相关分类