Note that there are some explanatory texts on larger screens.

plurals
  1. POMVC: Invoking overloaded constructors conditionally
    text
    copied!<p>I have an MVC application where I am implementing CQRS where I have seperated saving data from reading data into seperate interfaces. I am using constructor injection for injecting the concrete instances of these interfaces into the Controller. For constructor injection I am using Unity container. See below example</p> <pre class="lang-cs prettyprint-override"><code>//The Employee controller public class EmployeeController : Controller { IEmployeeRepository _Writer; IEmployeeQuery _Reader; //constructor injection public EmployeeController(IEmployeeRepository writer, IEmployeeQuery reader) { this._Writer = writer; this._Reader = reader; } //To Do: constructor injection for write operations only public EmployeeController(IEmployeeRepository writer) { this._Writer = writer; } //To Do: constructor injection for read operations only public EmployeeController(IEmployeeQuery reader) { this._Reader = reader; } } //Registration of the concrete types in the unity container. public static class Bootstrapper { public static void ConfigureUnityContainer() { IUnityContainer container = new UnityContainer(); container.RegisterType&lt;IEmployeeRepository, EmployeeRepository&gt;(new HttpContextLifetimeManager&lt;IEmployeeRepository&gt;()); container.RegisterType&lt;IEmployeeQuery, EmployeeQueries&gt;(new HttpContextLifetimeManager&lt;IEmployeeQuery&gt;()); ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(container)); } } //The derived Controller Factory for injection dependencies in the Controller constructor public class UnityControllerFactory : DefaultControllerFactory { IUnityContainer container; public UnityControllerFactory(IUnityContainer container) { this.container = container; } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { try { if (controllerType == null) { throw new ArgumentNullException("controllerType"); } if (!typeof(IController).IsAssignableFrom(controllerType)) { throw new ArgumentException(String.Format("Type requested is not a controller: {0}", controllerType.Name), "controllerType"); } return container.Resolve(controllerType) as IController; } catch (Exception) { return null; } } } </code></pre> <p>I have figured out that for any action I will either be fetching data or writing data but not both. In that case I need to invoke the controller constructors conditionally depending on which of "_Writer" or "_Reader" I need to initialize. </p> <p>How can this be done ?</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