gpt4 book ai didi

caSTLe-windsor - 温莎城堡和 IPrincipal

转载 作者:行者123 更新时间:2023-12-02 05:46:34 25 4
gpt4 key购买 nike

是否可以使用 CaSTLe Windsor 将 IPrincipal 注入(inject)到我的 asp.net mvc Controller 中。本文作者Scott Hanselman评论中有代码可以用结构图来做,但我不知道如何用 CaSTLe 来做。

更新:

这是我最终为我的 Controller 工厂所做的。请注意,大部分代码来自 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);
}
}

最佳答案

如果您使用的是 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...

这只是工厂设施配置的包装器。如果您使用的是以前的版本 (RC3),您可以 configure this with XML too .

关于caSTLe-windsor - 温莎城堡和 IPrincipal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1080915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com