Creating WindsorViewPageActivator - asp.net-mvc

I was playing with new Asp net mvc 3 RC2. I have created a WindsorViewPageActivator class as follows
public class WindsorViewPageActivator : IViewPageActivator
{
object IViewPageActivator.Create(ControllerContext controllerContext, Type type)
{
return DependencyResolver.Current.GetService(type);
}
}
and then a WindsorDependencyResolver class
public class WindsorDependencyResolver : IDependencyResolver
{
private readonly IWindsorContainer container;
public WindsorDependencyResolver(IWindsorContainer container)
{
this.container = container;
}
#region IDependencyResolver Members
public object GetService(Type serviceType)
{
return Resolve(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return container.ResolveAll(serviceType).Cast<object>();
}
public IEnumerable<TService> GetAllInstances<TService>()
{
return container.ResolveAll<TService>();
}
public TService GetInstance<TService>()
{
return (TService)Resolve(typeof(TService));
}
#endregion
private object Resolve(Type serviceType)
{
try
{
return container.Resolve( serviceType);
}
catch (Exception ex)
{
return null;
}
}
}
}
Now I am doing in Global.asax something like this
container.Register(Component.For<IControllerActivator>().ImplementedBy<WindsorControllerActivator>());
container.Register(Component.For<IViewPageActivator>().ImplementedBy<WindsorViewPageActivator>());
container.Register(Component.For<IControllerFactory>().ImplementedBy<DefaultControllerFactory>());
DependencyResolver.SetResolver (new WindsorDependencyResolver(container));
'
Now I am getting the following error
The view found at '~/Views/Account/LogOn.cshtml' was not created.
Do I need to register each view page in windsor container If yes then how can I register each view. I am using Razor view engine.
Thanks

Yes, in order to resolve stuff you need to register it. Have a look at the documentation to familiarise yourself with the API.

I have tried this myself, and unfortunately I can't seem to get it to work properly. I do the following in my solution:
public class WindsorViewPageActivator : IViewPageActivator
{
private readonly IKernel _kernel;
/// <summary>
/// Initializes a new instance of the <see cref="WindsorViewPageActivator"/> class.
/// </summary>
/// <param name="kernel">The kernel.</param>
public WindsorViewPageActivator([NotNull] IKernel kernel)
{
if (kernel == null) throw new ArgumentNullException("kernel");
_kernel = kernel;
}
public object Create(ControllerContext controllerContext, Type type)
{
if (!_kernel.HasComponent(type))
{
if (IsSupportedView(type))
{
_kernel.Register(Component.For(type).LifestylePerWebRequest());
}
else
{
return Activator.CreateInstance(type);
}
}
var viewPageInstance = _kernel.Resolve(type);
return viewPageInstance;
}
/// <summary>
/// Determines whether the specified type is of a supported view type.
/// </summary>
/// <param name="viewType">Type of the service.</param>
/// <returns>
/// <c>true</c> if the specified type is of a supported view type; otherwise, <c>false</c>.
/// </returns>
private static bool IsSupportedView(Type viewType)
{
return viewType.IsAssignableTo<WebViewPage>()
|| viewType.IsAssignableTo<ViewPage>()
|| viewType.IsAssignableTo<ViewMasterPage>()
|| viewType.IsAssignableTo<ViewUserControl>()
;
}
}
This works as long as you don't change anything in your markup. If you do, you'll get a registration error, as the view now will generate a new type, that doesn't exist in the container (but it has the same name!).
What I thought of doing, was to aggressively release the view component as soon as it's resolved, but I can't get rid of it in the container for some reason. Not even an explicit call to _kernel.ReleaseComponent(viewPageInstance) would do it (but that's of course just releasing the instance, not the type).
What we really need to do, is make Windsor inject properties into existing instances. That is, use Activator.CreateInstance(type) and then tell Windsor to inject the properties into the instance. But Windsor doesn't support injecting properties into existing instances, so we need to hack something together, that will do that for us.
I've seen this one http://www.jeremyskinner.co.uk/2008/11/08/dependency-injection-with-aspnet-mvc-action-filters/ (at the bottom), but that wouldn't perform very well.
My solution was simply to manually set my properties in the viewpage activator (you have a base viewpage type), but maybe there's some better solution?
EDIT
I managed to get it working after all!
My solution is to simply create a custom component activator and mimic what's being done in the MVC framework, like so:
public class ViewPageComponentActivator : DefaultComponentActivator
{
public ViewPageComponentActivator(ComponentModel model, IKernel kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
: base(model, kernel, onCreation, onDestruction)
{
}
protected override object CreateInstance(CreationContext context, ConstructorCandidate constructor, object[] arguments)
{
// Do like the MVC framework.
var instance = Activator.CreateInstance(context.RequestedType);
return instance;
}
}
The component activator simply always return a new instance of the view. Because the component is registered as being transient, CreateInstanceis always called. There might be some tweaking possibilities here.
The viewpage activator is now much simpler. Note that the type of service is different whenever you change the view, so we must register the type based on it's unique name (I haven't tweaked this yet, but there might be a nicer way to name the component).
/// <summary>
/// An activator using Castle Kernel for activating views.
/// </summary>
public class WindsorViewPageActivator : IViewPageActivator
{
private readonly IKernel _kernel;
/// <summary>
/// Initializes a new instance of the <see cref="WindsorViewPageActivator"/> class.
/// </summary>
/// <param name="kernel">The kernel.</param>
public WindsorViewPageActivator([NotNull] IKernel kernel)
{
if (kernel == null) throw new ArgumentNullException("kernel");
_kernel = kernel;
}
public object Create(ControllerContext controllerContext, Type type)
{
if (!_kernel.HasComponent(type.FullName))
{
_kernel.Register(Component.For(type).Named(type.FullName).Activator<ViewPageComponentActivator>().LifestyleTransient());
}
return _kernel.Resolve(type.FullName, type);
}
}
I hope this might be of use to someone in similar situations.

Related

ASP.NET MVC4 Unity - Resolve dependencies on another project

I have this configuration in my project MVC4 Unity and a generic configucion for drivers.
Bootstrapper.cs
namespace MyProyect.Web
{
public static class Bootstrapper
{
public static void Initialise()
{
var container = BuildUnityContainer();
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
container.RegisterType<MyProyect.Model.DataAccessContract.ICountryDao, MyProyect.DataAccess.CountryDao>();
container.RegisterType<MyProyect.Model.DataAccessContract.IContactDao, MyProyect.DataAccess.ContactDao>();
return container;
}
}
}
Global.asax:
protected void Application_Start()
{
...
Bootstrapper.Initialise();
...
}
GenericModelBinder.cs:
namespace MyProyect.Web.ModelBinder
{
public class GenericModelBinder : DefaultModelBinder//, IValueProvider
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var resolver = (Unity.Mvc4.UnityDependencyResolver)DependencyResolver.Current;
if (modelType == null)
{
return base.CreateModel(controllerContext, bindingContext, null);
}
return resolver.GetService(modelType);
}
}
}
Now that I need is to resolve a dependency in another project within the solution. My question is how I can do to that recognize the settings Unity in another project?. I currently I have this class but the current configuration does not bring in the MVC project.
namespace MyProyect.Model.ListData
{
public abstract class ListDataGenericResolver
{
protected T ResolverType<T>()
{
IUnityContainer container = new UnityContainer();
UnityServiceLocator locator = new UnityServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => locator);
//return unity.Resolve<T>();
return (T)container.Resolve(typeof(T));
}
}
}
this is a example how to use ListDataGenericResolver:
namespace MyProyect.Model.ListData.Types
{
public class CountryListData : ListDataGenericResolver, IGetListData
{
private readonly ICountryDao countryDao;
private string defaultValue;
public CountryListData(object defaultValue)
{
// Resolver
this.countryDao = this.ResolverType<ICountryDao>();
this.defaultValue = defaultValue == null ? string.Empty : defaultValue.ToString();
}
public IList<SelectData> GetData()
{
var data = this.countryDao.GetAllCountry(new Entity.Parameters.CountryGetAllParameters());
return data.Select(d => new SelectData
{
Value = d.CountryId.ToString(),
Text = d.Description,
Selected = this.defaultValue == d.CountryId.ToString()
}).ToList();
}
}
}
Thank you.
Here is how I do this.
In Application_Start, I create the unity container. I have a custom library that I use for all of my MVC projects that I import through NuGet, so I make the call to its configure method, then call the other project's Configure() methods. You could simply omit the custom library and add that code in here as well. All of that keeps my Application_Start nice and clean.
protected void Application_Start()
{
// Standard MVC setup
// <removed>
// Application configuration
var container = new UnityContainer();
new CompanyName.Mvc.UnityBootstrap().Configure(container);
new AppName.ProjectName1.UnityBootstrap().Configure(container);
new AppName.ProjectName2.UnityBootstrap().Configure(container);
// <removed>
}
This is the code for the custom MVC library's UnityBootstrap class
namespace CompanyName.Mvc
{
/// <summary>
/// Bootstraps <see cref="CompanyName.Mvc"/> into a Unity container.
/// </summary>
public class UnityBootstrap : IUnityBootstrap
{
/// <inheritdoc />
public IUnityContainer Configure(IUnityContainer container)
{
// Convenience registration for authentication
container.RegisterType<IPrincipal>(new InjectionFactory(c => HttpContext.Current.User));
// Integrate MVC with Unity
container.RegisterFilterProvider();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
return container;
}
}
}
Then, in the other projects, I have a UnityBootstrap there, that was called from Application_Start:
ProjectName1:
namespace AppName.ProjectName1
{
public class UnityBootstrap : IUnityBootstrap
{
public IUnityContainer Configure(IUnityContainer container)
{
return container.RegisterType<IDocumentRoutingConfiguration, DocumentRoutingConfiguration>();
}
}
}
ProjectName2: - and you can see in here, that this one depends on some other projects in another library and it is calling their Configure() methods to get them set up too...
namespace AppName.ProjectName2
{
public class UnityBootstrap : IUnityBootstrap
{
public IUnityContainer Configure(IUnityContainer container)
{
new CompanyName.Security.UnityBootstrap().Configure(container);
new CompanyName.Data.UnityBootstrap().Configure(container);
container.RegisterSecureServices<AuthorizationRulesEngine>(typeof(UnityBootstrap).Assembly);
return container
.RegisterType<IAuthorizationRulesEngine, AuthorizationRulesEngine>()
.RegisterType<IDateTimeFactory, DateTimeFactory>()
.RegisterType<IDirectoryInfoFactory, DirectoryInfoFactory>()
.RegisterType<IDirectoryWrapper, DirectoryWrapper>()
.RegisterType<IEmailService, EmailService>()
.RegisterType<IEntryPointService, EntryPointService>();
}
}
}
Here is the IUnityBootstrap interface that is used throughout the code above (for your reference)
/// <summary>
/// Defines a standard interface for bootstrapping an assembly into a Unity container.
/// </summary>
public interface IUnityBootstrap
{
/// <summary>
/// Registers all of the assembly's classes to their public interfaces and performs any other necessary configuration.
/// </summary>
/// <param name="container">The Unity container instance to configure.</param>
/// <returns>The same IUnityContainer object that this method was called on.</returns>
IUnityContainer Configure(IUnityContainer container);
}
I hope this helps you out.

Ninject : Constructor parameter

I am using Ninject together with ASP.NET MVC 4. I am using repositories and want to do constructor injection to pass in the repository to one of the controllers.
This is my Repository interface:
public interface IRepository<T> where T : TableServiceEntity
{
void Add(T item);
void Delete(T item);
void Update(T item);
IEnumerable<T> Find(params Specification<T>[] specifications);
IEnumerable<T> RetrieveAll();
void SaveChanges();
}
The AzureTableStorageRepository below is an implementation of IRepository<T>:
public class AzureTableRepository<T> : IRepository<T> where T : TableServiceEntity
{
private readonly string _tableName;
private readonly TableServiceContext _dataContext;
private CloudStorageAccount _storageAccount;
private CloudTableClient _tableClient;
public AzureTableRepository(string tableName)
{
// Create an instance of a Windows Azure Storage account
_storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);
_tableClient = _storageAccount.CreateCloudTableClient();
_tableClient.CreateTableIfNotExist(tableName);
_dataContext = _tableClient.GetDataServiceContext();
_tableName = tableName;
}
Note the tableName parameter needed because I was using a generic table repository to persist data to Azure.
And finally I have the following controller.
public class CategoriesController : ApiController
{
static IRepository<Category> _repository;
public CategoriesController(IRepository<Category> repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
_repository = repository;
}
Now I want to inject a repository into the controller. So I have created a module that contains the bindings:
/// <summary>
/// Ninject module to handle dependency injection of repositories
/// </summary>
public class RepositoryNinjectModule : NinjectModule
{
public override void Load()
{
Bind<IRepository<Category>>().To<AzureTableRepository<Category>>();
}
}
The loading of the module is done in the NinjectWebCommon.cs
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
// Load the module that contains the binding
kernel.Load(new RepositoryNinjectModule());
// Set resolver needed to use Ninject with MVC4 Web API
GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);
}
The DependencyResolver was created because Ninject's DependencyResolver implements System.Web.Mvc.IDependencyResolver and this cannot be assigned to GlobalConfiguration.Configuration of the WebApi Application.
So with all this in place, the Ninject part is actually injecting the right type in the Controller but Ninject cannot inject the tableName parameter in the constructor of AzureTableRepository.
How would I be able to do this in this case? I have consulted a lot of articles and the ninject documentation to see how I could use parameters, but I cannot seem to get it working.
Any help would be appreciated.
I'd use the WithConstructorArgument() method like...
Bind<IRepository<Category>>().To<AzureTableRepository<Category>>()
.WithConstructorArgument("tableName", "categories");
The rest of the repository design is probably another question. IMHO It seems like a big no no to create a table or do any heavy lifting in a ctor.
Meanwhile I have been playing around with Providers to try and do the trick and it seems to work.
I don't know if this is good idea or if it is overkill but here is what I have done:
I have created a generic provider class:
public abstract class NinjectProvider<T> : IProvider
{
public virtual Type Type { get; set; }
protected abstract T CreateInstance(IContext context);
public object Create(IContext context)
{
throw new NotImplementedException();
}
object IProvider.Create(IContext context)
{
throw new NotImplementedException();
}
Type IProvider.Type
{
get { throw new NotImplementedException(); }
}
}
And then I implemented that one in the AzureTableRepositoryProvider. (T to support having the same repository for multiple entity types.)
public class AzureTableRepositoryProvider<T> : Provider<AzureTableRepository<T>> where T : TableServiceEntity
{
protected override AzureTableRepository<T> CreateInstance(IContext context)
{
string tableName = "";
if (typeof(T).Name == typeof(Category).Name)
{
// TODO Get the table names from a resource
tableName = "categories";
}
// Here other types will be addedd as needed
AzureTableRepository<T> azureTableRepository = new AzureTableRepository<T>(tableName);
return azureTableRepository;
}
}
By using this provider I can pass in the right table name for the repository to work with. But for me, two questions remain:
Is this good practice or could we do things much simpler?
In the NinjectProvider class I have two notImplementedException cases. How could I resolve these? I used sample code from the following link but that does not work as the Provider is abstract and the code does not have a body for the create method... enter link description here

No Parameterless constructor defined for this object...With a twist?

I'm building an MVC4 app using EF5 and ninject. Something broke when I upgraded from MVC3 to 4. So I created a brand new solution, got all my nuget packages, added all my references, then copied in my code.
Project builds, thats fabulous.
My problem is the (Ninjection) sp? doesn't seem to be wiring up correctly. I get the "No Parameterless constructor defined for this object" as a runtime error when I try to load the page. However, if I simply add an empty public parameterless constructor, the page renders and all is right with the world.
My App_Start Code runs fine, NinjectWebCommon.cs (included at the bottom of the question) I've stepped through the code, but other that copying and pasting, and following tutorials online. I don't understand IoC well enough to know what to do next.
namespace search.Controllers
{
public class HomeController : Controller
{
ICamaService _service = null;
[Inject]
public HomeController(ICamaService service)
{
_service = service;
}
************** ADDING THIS FIXES THE RUNTIME ERROR *********
public HomeController(){
;
}
***********
//TODO: ADD ACTIONS
public ViewResult Index()
{
return View();
}
}
}
Here is my composition root:
[assembly: WebActivator.PreApplicationStartMethod(typeof(search4.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(search4.App_Start.NinjectWebCommon), "Stop")]
namespace search4.App_Start
{
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using search.Services;
using search.Data;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
public static void Stop()
{
bootstrapper.ShutDown();
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ICamaContext>().To<CamaContext>().InRequestScope();
kernel.Bind<ICamaService>().To<CamaService>().InRequestScope();
}
}
}
![Screen Capture of Exception][1]
http://shareimage.ro/viewer.php?file=svs5kwamqy0pxbyntig4.gif
I am not a Ninject user, but from my experiences with other IOC frameworks in MVC, you would need to replace the DefaultControllerFactory with an implementation that injects objects instead of requiring a default constructor.
Looks like your bindings arn't being registered propertly.
Im not sure exactly what's wrong, but I create a NinjectApplicationModule that works for me:
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Load(new NinjectApplicationModules());
}
public class NinjectApplicationModules : NinjectModule
{
/// <summary>
/// Loads the Binding module into the kernel. Used to map Abstract Classes to Concrete classes at runtime.
/// </summary>
public override void Load()
{
// Bindings...
Bind<ICamaContext>().To<CamaContext>().InRequestScope();
Bind<ICamaService>().To<CamaService>().InRequestScope();
}
}
Check you data model class.
Public Class A ()
{
public A() {
}
public string Name{get; set;}
}
But you need to remove this default Class A Constructor.
Public Class A ()
{
public string Name{get; set;}
}
I was already facing No Parameter less constructor defined for this object

Whats the difference between using these 2 methods?

I upgraded from ninject 2.0 to 2.2 and nothing works anymore.
When I use nuget it makes this
[assembly: WebActivator.PreApplicationStartMethod(typeof(MvcApplication3.App_Start.NinjectMVC3), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(MvcApplication3.App_Start.NinjectMVC3), "Stop")]
namespace MvcApplication3.App_Start
{
using System.Reflection;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Mvc;
public static class NinjectMVC3
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
DynamicModuleUtility.RegisterModule(typeof(HttpApplicationInitializationModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
RegisterServices(kernel);
return kernel;
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
}
}
}
I use this
/// <summary>
/// Application_Start
/// </summary>
protected void Application_Start()
{
// Hook our DI stuff when application starts
IKernel kernel = SetupDependencyInjection();
}
public IKernel SetupDependencyInjection()
{
IKernel kernel = CreateKernel();
// Tell ASP.NET MVC 3 to use our Ninject DI Container
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
return kernel;
}
protected IKernel CreateKernel()
{
var modules = new INinjectModule[]
{
new NhibernateModule(),
new ServiceModule(),
new RepoModule()
};
public class NinjectDependencyResolver : IDependencyResolver
{
private readonly IResolutionRoot resolutionRoot;
public NinjectDependencyResolver(IResolutionRoot kernel)
{
resolutionRoot = kernel;
}
public object GetService(Type serviceType)
{
return resolutionRoot.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return resolutionRoot.GetAll(serviceType);
}
}
So when I try to use my way(what worked before the changes) when I load it up now I get some no parameterless controller.
When I use their I get
Error occured: Error activating SomeController
More than one matching bindings are available.
Activation path:
1) Request for SomeController
Suggestions:
1) Ensure that you have defined a binding for SomeController only once.
I hope you know that there is a documentation at https://github.com/ninject/ninject.web.mvc/wiki/Setting-up-an-MVC3-application where this question is explained.
Move your module array into the
var modules = new INinjectModule[]
{
new NhibernateModule(),
new ServiceModule(),
new RepoModule()
};
into the RegisterServices and add
kernel.Load(modules);
Those are two different approaches into configuring the kernel. The approach you were using requires modifying Global.asax. The NuGet package uses this new feature of ASP.NET 4 which allows dynamic modules to be registered at application startup. Because the authors of the NuGet package didn't want to mess up with Global.asax as there might be some other existing code, they preferred to use this separate file for configuring the kernel.
The two approaches are not compatible and you should never use them both in the same application. The new version also already contains a NinjectDependencyResolver so you no longer need to write or set any custom DependencyResolver.SetResolver.
All you need to do is use the RegisterServices static method in the bootstrapper class to configure your kernel:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ISomeControllerDependency>().To<SomeConcreteImpl>();
}
And if you had some NInject modules that you wanted to load:
private static void RegisterServices(IKernel kernel)
{
kernel.Load(
new NhibernateModule(),
new ServiceModule(),
new RepoModule()
);
}
That's it. Don't forget to remove any NInject trace from your Global.asax to avoid any conflicts.
I guess the reason your code didn't work with the first approach is because you didn't load the modules in the RegisterServices method.

IoC Castle Windsor in MVC routing problem

I've set up castle windsor in my mvc app. everything works great except it also catches routes that are of type link or image. The problem is that right before exiting from the controller and generating the view "GetControllerInstance" is executed with 'null' type. This happends anytime there a link on a page like:
<link rel="stylesheet" type="text/css" href="non-existing.css"/>
Or a link to an image that does not exist. Why is this happening?
My windows class:
public class WindsorControllerFactory : DefaultControllerFactory
{
#region Constants and Fields
/// <summary>
/// The container.
/// </summary>
private readonly WindsorContainer container;
#endregion
// The constructor:
// 1. Sets up a new IoC container
// 2. Registers all components specified in web.config
// 3. Registers all controller types as components
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="WindsorControllerFactory"/> class.
/// </summary>
public WindsorControllerFactory()
{
// Instantiate a container, taking configuration from web.config
this.container = InversionOfControl.Container;
// Also register all the controller types as transient
IEnumerable<Type> controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
foreach (Type t in controllerTypes)
{
this.container.AddComponentLifeStyle(t.FullName, t, LifestyleType.Transient);
}
}
#endregion
#region Methods
/// <summary>
/// The get controller instance.
/// </summary>
/// <param name="requestContext">
/// The request context.
/// </param>
/// <param name="controllerType">
/// The controller type.
/// </param>
/// <returns>
/// Resolved controller instance.
/// </returns>
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
controllerType = typeof(HomeController);
}
return (IController)this.container.Resolve(controllerType);
}
#endregion
}
This is only natural. The non-existing image or css cannot find the controller but you are defaulting it to the HomeController while this controller cannot handle static content.
I do not think you need an override here. Let the default controller handle what it does and resource will get a 404 error if it cannot be found instead you forcing it to be served by that controller.
As I said, it is only natural for the type to be null if it cannot be found.
Change it to this:
if (controllerType == null)
{
return base.GetControllerInstance(requestContext, controllerType);
}
I found that I had to return null when the controllerType was null. Handing it on to the base class resulted in an exception. Below is the working code that I am using.
public class DependencyControllerFactory : DefaultControllerFactory, IDisposable
{
protected readonly WindsorContainer _container;
public DependencyControllerFactory()
{
_container = new WindsorContainer();
_container.Kernel.Resolver.AddSubResolver(new CollectionResolver(_container.Kernel));
_container.Install(FromAssembly.This());
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
return null;
}
else
{
return (IController)_container.Resolve(controllerType);
}
}
public override void ReleaseController(IController controller)
{
_container.Release(controller);
}
public void Dispose()
{
_container.Dispose();
}
}

Resources