I want to register controllers programatically in Global.asax.cs. with MvcContrib.Castle.WindsorControllerFactory
private static IWindsorContainer _Container;
protected virtual void InitializeWindsor()
{
try
{
if (_Container == null)
{
_Container = new WindsorContainer();
ControllerBuilder.Current.SetControllerFactory(new MvcContrib.Castle.WindsorControllerFactory(_Container));
RegisterActiveRecord();
RegisterRepositories();
RegisterServices();
RegisterControllers();
RegisterComponents();
}
I have done it by
private void RegisterControllers()
{
try
{
_Container.Register(
AllTypes.Of<IController>()
.FromAssembly(typeof(HomeController).Assembly)
.Configure(c => c.LifeStyle.Transient)
);
It works fine for all controllers with default constructors. But, I have a controller (LoginController) with parameterzied construtor.
public class LoginController : Controller
{
private IUser _User;
public LoginController(IUser objUser)
{
_User = objUser;
}
When I tried to view it in browser (http://localhost:2011/Login), it gives me following error.
**No parameterless constructor defined for this object**
Stack Trace:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
System.Activator.CreateInstance(Type type) +6
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +491
[InvalidOperationException: An error occurred when trying to create a controller of type 'NAATEELib.Controllers.LoginController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +628
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +204
Please guide me. I do not want to modify .config (xml) files. thanks.
It seems you forgot to use a Windsor controller factory (the stack trace shows DefaultControllerFactory).
Take a look at this Windsor - ASP.NET MVC tutorial, in particular part 2.
EDIT: OP edited the question, code is already using MvcContrib's Windsor controller factory. Either the registrations are wrong (recommend using MvcContrib's RegisterControllers) or the controller factory isn't correctly installed.