c# - SqlClient connection factory management, with ninject in a WCF service -
i'm running problem in wcf service. "the timeout period elapsed prior obtaining connection pool"
now understand error, question is, proper way manage sql connection in wcf service using ninject.
what have done this. in binding have
bind<iconnectionfactory>().to<connectionfactory>().inscope(c => operationcontext.current);
and connection factory looks this.
public class connectionfactory : iconnectionfactory { private string connectionstring = configurationmanager.connectionstrings["sqlconnection"].connectionstring; private sqlconnection sqlconnection; public sqlconnection getopenconnection() { if (sqlconnection == null) sqlconnection = new sqlconnection(connectionstring); if (sqlconnection.state != connectionstate.open) sqlconnection.open(); return sqlconnection; } public void closeconnection() { sqlconnection.close(); }
whenever need sql connection invoke via ioc container this.
sqlconnection connection = ioc.resolve<iconnectionfactory>().getopenconnection();
my assumption was, whenever dealing same request, same connection ninject, , connection calls within request life time same connection. based on error, assuming not happening. there better way of doing ? or better connection management paradigm wcf ninject ? feel making connection factory singleton wrong way go, that's gut feeling.
edit: add inject connection repositories this
private readonly sqlconnection connection; public randomrepository(iconnectionfactory connectionfactory) { connection = connectionfactory.getopenconnection(); }
hy, can install ninject.extensions.wcf provides appropriate scoping wcf services. can inject sqlconnection
directly classes without having use connection factory. use method binding appropriate scope. example call scope:
bind<isqlconnection>().tomethod(ctx => ctx.kernel.get<iconnectionfactory>().getopenconnection()).incallscope();
ninject take care of disposing connection when request out of scope.
Comments
Post a Comment