Note that there are some explanatory texts on larger screens.

plurals
  1. POContextual / Conditional dependency injection with depth greater than 1 with Ninject?
    text
    copied!<p>I have a <code>IDataContext</code> interface implemented by a <code>InMemoryDataContext</code> and <code>MyApplicationDataContext</code>. This is consumed by all of my repositories which are defined as <code>BananaRepository : IBananaRepository</code> and take the data context in their constructor:</p> <pre><code>interface IDataContext {} class InMemoryDataContext : IDataContext {} class MyApplicationDataContext : IDataContext {} interface IBananaRepository {} class BananaRepository : IBananaRepository { public BananaRepository(IDataContext dataContext) {} } </code></pre> <p>So far my consumers of the interfaces and services are ASP.NET MVC controllers, synchronous commands and queries. NInject is configured in my Web project and <code>IDataContext</code> is bound to <code>MyApplicationDataContext</code> with <code>InRequestScope()</code>.</p> <pre><code> kernel.Bind&lt;IDataContext&gt;().To&lt;MyApplicationDataContext&gt;().InRequestScope(); kernel.Bind&lt;IBananaRepository&gt;().To&lt;BananaRepository&gt;(); </code></pre> <p>I have reached the point in the evolution of my project where I want to start adding asynchronous processing (commands, events+handlers, etc). The problem I am facing is that for those I need to get a transient <code>IDataContext</code> (new one each time) but the binding is already set-up for a <code>IDataContext</code> instance per request for my controllers.</p> <p>Consider this simple scenario, where my <code>DoSomethingAsyncCommand</code> will execute on a new thread:</p> <pre><code>class DoSomethingAsyncCommand : IAsyncCommand&lt;TArgs&gt; { public DoSomethingAsyncCommand(IBananaRepository repository) {} public bool Execute(TArgs args) {} } </code></pre> <p>I want when NInject instantiates a class implementations of <code>IAsyncCommand</code> the <code>IBananaRepository</code> (and all my other repositories) to be initialized with a new instance of <code>IDataContext</code> rather than the one for the web request to be reused (effectively I want for <code>IAsyncCommand</code> my <code>IDataContext</code> to be bound as <code>InTransientScope()</code>)</p> <p>How can I do that?</p> <p>P.S: I am using the CommonServiceLocator rather than the Ninject kernel directly to instantiate IAsyncCommand instances.</p>
 

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