Note that there are some explanatory texts on larger screens.

plurals
  1. POReturning different components in different scopes with Autofac
    primarykey
    data
    text
    <p>I have two scopes, one nested inside the other. When I resolve a particular service, I would like one component to be resolved in one root scope and a different one in the child scope. Is there an easy way of doing this?</p> <p>I have managed to get something working using a factory class that determines what the current scope is and then returning the appropriate instance:</p> <pre><code>IContainer BuildContainer() { var builder = new ContainerBuilder(); // ... builder.RegisterType&lt;FooInParentScope&gt;().AsSelf(); builder.RegisterType&lt;FooInChildScope&gt;().AsSelf(); builder.RegisterType&lt;FooFactory&gt;().AsImplementedInterfaces(); builder.Register&lt;IFoo&gt;(c =&gt; c.Resolve&lt;IFooFactory&gt;().GetFoo()).InstancePerLifetimeScope(); // ... } class FooFactory : IFooFactory { private readonly ILifetimeScope m_scope; public FooFactory(ILifetimeScope scope) { m_scope = scope; } public IFoo GetFoo() { if (m_scope.Tag == "ParentScope") return m_scope.Resolve&lt;FooInParentScope&gt;(); else return m_scope.Resolve&lt;FooInChildScope&gt;(); } } class FooInParentScope : IFoo { } class FooInChildScope : IFoo { } </code></pre> <p>There are a number of issues with this approach:</p> <ol> <li>I have to add an extra class (or 2 - not sure if the IFooFactory is really necessary)</li> <li>The code above does not cope with other scopes that are nested in ParentScope. I can fix this by casting the scope to <code>Autofac.Core.Lifetime.LifetimeScope</code> and examining the <code>ParentLifetimeScope</code> property, but that is probably not a particularly safe thing to do.</li> </ol>
    singulars
    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. 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