开发者

How to wire up a controller's dependancy

So I went through the asp.net mvc tutorial for castle windsor, and my registrations look like:

    private static IWindsorContainer _container = new WindsorContainer();
    private static void BootstrapContainer()
    {
        _container = new WindsorContainer()
            .Install(FromAssembly.This());
        var controllerFactory = new WindsorControllerFactory(_container.Kernel);
      开发者_Python百科  ControllerBuilder.Current.SetControllerFactory(controllerFactory);
    }
    protected void Application_End()
    {
        _container.Dispose();
    }

So in my HomeController I have this:

public class HomeController : Controller
{
    private IUserService _userService;

    public HomeController(IUserService userService)
    {
        this._userService = userService;
    }
}

How would I go about wiring this controller up to setup the IUserService?

Update In case in matters how I need to wire things up, my vs.net projects are:

web, interfaces, entities, data (nhibernate), services


The implementation of WindsorControllerFactory should look like this from the 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);
   } 
}

UPDATED

Each interface that needs to be resolved by dependancy injection need to be registered.

This can be done by calling the .Register method on the container.

container.Register(Component.For<IUserService>().ImplementedBy<UserService>().LifeStyle.Transient);

More info here: http://docs.castleproject.org/Windsor.Registering-components-one-by-one.ashx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜