Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>An alternative to passing the constructor arguments at resolve-time is to encode those arguments in the registration function:</p> <pre><code>builder .Register(c =&gt; new ConnectionFactory("127.0.0.1", 80)) .As&lt;IConnectionFactory&gt;() .SingleInstance(); </code></pre> <p>Autofac will use that function whenever it needs to create the connection factory instance.</p> <p>Since we configured <code>ConnectionFactory</code> as <code>SingleInstance</code>, it will be shared amongst all components which depend on <code>IConnectionFactory</code>. This means <code>ConnectionFactory</code> needs to keep its own state between calls to <code>CreateConnection</code>:</p> <pre><code>public class ConnectionFactory : IConnectionFactory { private int _fromPort; public ConnectionFactory(string ip, int fromPort) { ... _fromPort = fromPort; } public IConnection CreateConnection() { return new Connection(ip, _fromPort++); } } </code></pre> <p>If you have a one-off <code>ConnectionFactory</code> which, say, uses a different IP, you can use a named registration:</p> <pre><code>builder .Register(c =&gt; new ConnectionFactory("192.168.0.1", 80)) .Named&lt;IConnectionFactory&gt;("AlernateConnectionFactory") .SingleInstance(); </code></pre> <p>When you want a component to use that particular factory instead of the default one, you can use the <a href="http://code.google.com/p/autofac/wiki/TypedNamedAndKeyedService" rel="noreferrer"><code>ResolveNamed</code> method</a>:</p> <pre><code>builder.Register(c =&gt; new Foo(c.ResolvedNamed&lt;IConnectionFactory&gt;("AlernateConnectionFactory"))); </code></pre> <p>This is a handy technique to configure a type in multiple ways and use them in specific places.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload