温莎城堡和IPrincipal

bec*_*lmw 2 castle-windsor

有可能使用Castle Windsor将IPrincipal注入我的asp.net mvc控制器.Scott Hanselman的这篇文章在评论中有代码用结构图来做,但我无法弄清楚如何用Castle做到这一点.

更新:

这是我最终为我的控制器工厂所做的事情.请注意,大多数代码来自Steve Sanderson的Pro ASP.NET MVC书籍,并添加了以下答案中的代码.

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<FactorySupportFacility>();
        _container.Register(Component.For<IPrincipal>()
          .LifeStyle.PerWebRequest
          .UsingFactoryMethod(() => 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);
    }        
}
Run Code Online (Sandbox Code Playgroud)

Mau*_*fer 11

如果您使用的是Windsor 2.0,则无需修改ControllerFactory:

var container = new WindsorContainer();
container.AddFacility<FactorySupportFacility>();
container.Register(Component.For<IPrincipal>()
  .LifeStyle.PerWebRequest
  .UsingFactoryMethod(() => HttpContext.Current.User));
// your component registrations...
Run Code Online (Sandbox Code Playgroud)

这只是Factory工厂配置的包装.如果您使用的是以前的版本(RC3),则也可以使用XML进行配置.