新人与城堡windsor,并试图创建我的接口的实现

时间:2012-12-26 18:07:36

标签: c# .net castle-windsor

我已经创建了自己的项目但是我没有使用城堡来实现我的接口实现!我添加了下面显示的ControllersInstallerWindsorControllerFactory类。我的控制器是下面的最后一段代码。 请帮忙! 谢谢, 詹姆斯

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 new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
        }
        return (IController)kernel.Resolve(controllerType);
    }
}



public class ControllersInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
                        .BasedOn<IController>()
                        .LifestyleTransient());
    }
}






 public class HomeController : Controller
{
    public IMemberMapper _memberMapper;

    public HomeController()
    {
    }

    public HomeController(IMemberMapper memberMapper)
    {
        _memberMapper = memberMapper;
    }

    public ActionResult Index()
    {
        var model = _memberMapper.Map();
        return View(model);
    }
}

//全局文件

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();
    }

    private static IWindsorContainer container;

    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();
    }
}

2 个答案:

答案 0 :(得分:0)

您是否已将WindsorControllerFactory注册为当前的ControllerFactory

这通常在Globals.asax.cs中完成。如果您没有这样做,请查看此示例:https://github.com/kkozmic/ToBeSeen/blob/master/src/ToBeSeen/Global.asax.cs

更具体地说,查看BootstrapContainer()方法及其调用位置。这指示ASP.NET MVC尝试使用新定义的工厂创建它可能需要的任何控制器。如果没有这一步,您只需使用内置控制器工厂。

答案 1 :(得分:0)

您必须在某处注册IMemberMapper服务。最佳位置是另一个用于此目的的安装程序类。