所以我浏览了windsor城堡的asp.net mvc教程,我的注册看起来像:
private static IWindsorContainer _container = new WindsorContainer();
private static void BootstrapContainer()
{
_container = new WindsorContainer()
.Install(FromAssembly.This());
var controllerFactory = new WindsorControllerFactory(_container.Kernel);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
}
protected void Application_End()
{
_container.Dispose();
}
所以在我的HomeController中我有这个:
public class HomeController : Controller
{
private IUserService _userService;
public HomeController(IUserService userService)
{
this._userService = userService;
}
}
如何连接此控制器以设置IUserService?
更新的 如果我需要连接起来,我的vs.net项目是:
web, interfaces, entities, data (nhibernate), services
答案 0 :(得分:2)
WindsorControllerFactory的实现应该来自doco http://docs.castleproject.org/Windsor.Windsor-tutorial-part-two-plugging-Windsor-in.ashx?HL=ikernel。
public class WindsorControllerFactory : DefaultControllerFactory
{
private readonly IKernel kernel;
public WindsorControllerFactory(IKernel kernel)
{
this.kernel = kernel;
}
public override void ReleaseController(IController controller)
{
kernel.ReleaseComponent(controller);
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
// Throw exception. Can't resolve null type.
}
return (IController)kernel.Resolve(controllerType);
}
}
<强>已更新强>
需要通过依赖注入解析的每个接口都需要注册。
这可以通过调用容器上的.Register方法来完成。
container.Register(Component.For<IUserService>().ImplementedBy<UserService>().LifeStyle.Transient);
此处有更多信息:http://docs.castleproject.org/Windsor.Registering-components-one-by-one.ashx