Note that there are some explanatory texts on larger screens.

plurals
  1. POCastle Windsor and IPrincipal
    primarykey
    data
    text
    <p>Is is possible to inject IPrincipal using Castle Windsor into my asp.net mvc controller. This article by <a href="http://www.hanselman.com/blog/IPrincipalUserModelBinderInASPNETMVCForEasierTesting.aspx" rel="nofollow noreferrer">Scott Hanselman</a> has code in the comments to do it with structure map, but I cannot figure out how to do it with Castle.</p> <p>Update:</p> <p>Here is what I ended up with for my controller factory. Note that most of the code is from Steve Sanderson's Pro ASP.NET MVC book with the addition of the code from the answers below.</p> <pre><code>public class WindsorControllerFactory : DefaultControllerFactory { readonly WindsorContainer _container; // The constructor: // 1. Sets up a new IoC container // 2. Registers all components specified in web.config // 3. Registers IPrincipal // 4. Registers all controller types as components public WindsorControllerFactory() { // Instantiate a container, taking configuration from web.config _container = new WindsorContainer( new XmlInterpreter(new ConfigResource("castle")) ); _container.AddFacility&lt;FactorySupportFacility&gt;(); _container.Register(Component.For&lt;IPrincipal&gt;() .LifeStyle.PerWebRequest .UsingFactoryMethod(() =&gt; HttpContext.Current.User)); // Also register all the controller types as transient var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes() where typeof(IController).IsAssignableFrom(t) select t; foreach (var t in controllerTypes) _container.AddComponentLifeStyle(t.FullName, t, LifestyleType.Transient); } // Constructs the controller instance needed to service each request protected override IController GetControllerInstance(Type controllerType) { return (IController)_container.Resolve(controllerType); } } </code></pre>
    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.
 

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