问题
I'm trying to use autofac in the following scenario:
A WCF service that, on every method call, receives connection details which it uses to open a DB connection.
(i.e. public UserDTO GetUser(string dbUsername, string dbPassword, int userId)
.
Since opening a DB connection is common to all methods, I'd like to use an IParameterInspector
to intercept every method call, extract the connection details, and initialize the connection.
My problems are-
1. I don't know if (and how) I can inject the necessary factory to my IParameterInspector
2. Once I've created my connection, I'm not sure as to how I can register it with my container so that it'll be available to all components for that request.
My IParameterInspector
so far:
public object BeforeCall(string operationName, object[] inputs)
{
var userName = inputs[0] as Guid?;
var password = inputs[1] as string;
// How do I inject the ConnectionsFactory?
var connection = ConnectionsFactory.CreateConnection(userName, password);
// How can I register my connection in the container, so that it'll be available to all dependencies created in this call?
return null;
}
thanks
回答1:
Ok, figured it out-
My problem was that IParameterInspector
was invoked after my service class was instanciated. So obviously that wasn't the place to do initializations.
Implementing a IInstanceCreator
proved to be the right thing to do, since it's invoked before the creation of the service class, and is actually used to tell WCF how to create a service class.
I just created an autofac Lifetime Scope, and registered my DB Connection with it.
来源:https://stackoverflow.com/questions/12050091/ioc-using-autofac-and-wcf-iparameterinspector