[[sftp-dsf]]
= Delegating Session Factory

Version 4.2 introduced the `DelegatingSessionFactory`, which allows the selection of the actual session factory at runtime.
Prior to invoking the SFTP endpoint, you can call `setThreadKey()` on the factory to associate a key with the current thread.
That key is then used to look up the actual session factory to be used.
You can clear the key by calling `clearThreadKey()` after use.

We added convenience methods so that you can more easily do so from a message flow, as the following example shows:

[source, xml]
----
<bean id="dsf" class="org.springframework.integration.file.remote.session.DelegatingSessionFactory">
    <constructor-arg>
        <bean class="o.s.i.file.remote.session.DefaultSessionFactoryLocator">
            <!-- delegate factories here -->
        </bean>
    </constructor-arg>
</bean>

<int:service-activator input-channel="in" output-channel="c1"
        expression="@dsf.setThreadKey(#root, headers['factoryToUse'])" />

<int-sftp:outbound-gateway request-channel="c1" reply-channel="c2" ... />

<int:service-activator input-channel="c2" output-channel="out"
        expression="@dsf.clearThreadKey(#root)" />
----

IMPORTANT: When using session caching (see xref:sftp/session-caching.adoc[SFTP Session Caching]), each of the delegates should be cached.
You cannot cache the `DelegatingSessionFactory` itself.

Starting with version 5.0.7, the `DelegatingSessionFactory` can be used in conjunction with a `RotatingServerAdvice` to poll multiple servers; see xref:sftp/rotating-server-advice.adoc[Inbound Channel Adapters: Polling Multiple Servers and Directories].

