开发者

"No parameterless constructor" error instantiating Controller registered w/Windsor Container

Using MVC and trying to use dependency injection for controllers, but when I try to call a method on a controller that takes a dependency, I get the "no parameterless constructor" error. Here's my setup:

ProductRepository : IProductRepository


ProductService : IProductService {
     public ProductService(IProductRepository repository) {} }

ProductController {
     public ProductController(IProductService service) {} }

In Global.asax:

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        InitializeServiceLocator();
        RegisterRoutes(RouteTable.Routes);
    }


    protected virtual void InitializeServiceLocator()
    {
        IWindsorContainer container = new WindsorContainer();
        ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));

        container.RegisterControllers(typeof(HomeController).Assembly);
        ComponentRegistrar.AddComponentsTo(container);
        foreach (var handler in container.Kernel.GetAssignableHandlers(typeof(object)))
        {
            System.Diagnostics.Debug.WriteLine(String.Format("{0} {1}",
               handler.Compone开发者_运维技巧ntModel.Service,
               handler.ComponentModel.Implementation));
        }

        ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
    }

ComponentRegistrar:

public static void AddComponentsTo(IWindsorContainer container)
{
    AddCustomRepositoriesTo(container);
    AddApplicationServicesTo(container);
}

When InitializeServiceLocator completes, I can see that all Controllers, Services and Repositories are registered.

Any help greatly appreciated.


I'd still like to know the problem, but I've worked around it by creating my own WindsorControllerFactory per this post (with modification to avoid any web.config action): http://mvcsharp.wordpress.com/2010/01/09/setting-up-ioc-in-asp-net-mvc-using-castle-windsor/

The WindsorControllerFactory in the previous code was the MvcContrib.Castle.WindsorControllerFactory. Anyone using MvcContrib version successfully?

Thanks.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜