1 回答
TA贡献1804条经验 获得超2个赞
实际上,InstancePerLifetimeScope()就是您要寻找的解决方案。您需要做的就是注入 DbConnection工厂,该工厂生成DbConnection 的拥有(docs link 1和docs link 2)实例,而不是 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
}
}
}
它确实改变了作为请求作用域的子作用域的行为,但我不确定这是否是您的代码的问题 - 试一试,它应该可以正常工作。如果没有,那么你知道去哪里问。;)
- 1 回答
- 0 关注
- 129 浏览
添加回答
举报