I am introducing DI into my MS MVC application and I am having trouble getting the controllers instantiated from within my custom Controller Factory. It seems that the overridden "GetControllerInstance" is not being called.
Can someone tell me what I am missing?
My Controller Factory:
public class WindsorControllerFactory : DefaultControllerFactory
{
readonly IWindsorContainer container;
public WindsorControllerFactory(IWindsorContainer container)
{
this.container = container;
var controllerTypes =
from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
foreach (var t in controllerTypes)
container.Register(Component.For(t).LifeStyle.Transient);
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null) return null;
return (IController)container.Resolve(controllerType);
}
}
Bootstrap:
public static void Bootstrap()
{
RouteConfigurator.RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(IoC.Container));
WindsorConfigurator.Configure();
.
.
}
IoC:
public static class IoC
{
private static readonly object LockObj = new object();
private static IWindsorContainer container = new WindsorContainer();
public static IWindsorContainer Container
{
get { return container; }
set
{
lock (LockObj)
{
container = value;
}
}
}
public static T Resolve<T>()
{
return container.Resolve<T>();
}
public static object Resolve(Type type)
{
return container.Resolve(type);
}
}
WindsorRegistrar:
public class WindsorRegistrar
{
public static void RegisterSingleton(Type interfaceType, Type implementationType)
{
IoC.Container.Register(Component.For(interfaceType).ImplementedBy(implementationType).LifeStyle.Singleton);
}
public static void Register(Type interfaceType, Type implementationType)
{
IoC.Container.Register(Component.For(interfaceType).ImplementedBy(implementationType).LifeStyle.PerWebRequest);
}
public static void RegisterAllFromAssemblies(string a)
{
IoC.Container.Register(AllTypes.FromAssemblyNamed(a).Pick().WithService.FirstInterface().LifestylePerWebRequest());
}
}
HELP PLEASE ?
CodePudding user response:
There is a Nuget package that makes Windsor integration into MVC application friction-less.
PM> Install-Package Castle.Windsor.Web.Mvc
CodePudding user response:
I can't spot any mistake at the first sight... But for sure your plumbing is redundant... Keept it simple as per windsor tutorial