1 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
實(shí)際上,InstancePerLifetimeScope()就是您要尋找的解決方案。您需要做的就是注入 DbConnection工廠,該工廠生成DbConnection 的擁有(docs link 1和docs link 2)實(shí)例,而不是 DbConnection 本身。
// registration
builder.RegisterType<SqlConnection>()
.As<IDbConnection>()
.WithParameter(new NamedParameter("connectionString", WebConfigUtils.DefaultConnectionString))
.InstancePerLifetimeScope();
// usage
public class GetRolePermissions
{
public class Command: IRequest<List<string>>
{
public ICollection<AspNetUserRole> UserRoles { get; set; }
}
public class Handler : AsyncRequestHandler<Command, List<string>>
{
private Func<Owned<IDbConnection>> _connectionFactory;
public Handler(Func<Owned<IDbConnection>> connectionFactory)
{
_connectionFactory = connectionFactory;
}
// not really sure where your consuming code is, so just something off the top of my head
public DontKnowYourResultType Handle(GetRolePermissions.Command cmd) {
using (var ownedConnection = _connectionFactory()) {
// ownedConnection.Value is the DbConnection you want
// ... do your stuff with that connection
} // and connection gets destroyed upon leaving "using" scope
}
}
}
它確實(shí)改變了作為請(qǐng)求作用域的子作用域的行為,但我不確定這是否是您的代碼的問(wèn)題 - 試一試,它應(yīng)該可以正常工作。如果沒(méi)有,那么你知道去哪里問(wèn)。;)
- 1 回答
- 0 關(guān)注
- 152 瀏覽
添加回答
舉報(bào)