是可能使用温莎城堡到我的asp.net mvc的控制器注入的IPrincipal。这篇由Scott Hanselman撰写的文章在注释中使用了结构映射的代码,但我无法弄清楚如何使用Castle来完成它。温莎城堡和IPrincipal的
更新:
这是我最终为我的控制器工厂。请注意,大部分代码来自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);
}
}
我不会注册的控制器工厂内的设施和IPrincipal的,他们是不相关的,应该是分开的。 – 2009-10-07 15:28:29