asp mvc 2 structure map not working when deployed - c#

I'm using structure map in my asp mvc site, which i've just tried to deploy onto II6 for the first time.
The basic dependency structure is very typical:
public ControlMController(IControlMService controlMservice)
{
this._controlMservice = controlMservice;
}
...
public ControlMService(IControlMRepository repo)
{
this._repo = repo;
}
...
public SQLControlMRepository (CTRLMDataContext dataContext)
{
_db = dataContext;
}
My structureMap Registry is like this
For<IControlMService>().Use<ControlMService>();
For<IControlMRepository>().Use<SQLControlMRepository>();
//For<IControlMRepository>().Use<TestControlMRepository>();
SelectConstructor<CTRLMDataContext>(() => new CTRLMDataContext());
For<CTRLMDataContext>().LifecycleIs(new HybridLifecycle()).Use<CTRLMDataContext>();
My Controller Factory looks like this:
public class ControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
try
{
if (controllerType == null) return base.GetControllerInstance(requestContext,controllerType);
return ObjectFactory.GetInstance(controllerType) as IController;
}
catch
{
System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
return null;
}
}
}
This works 100% on the development server, but it does not work on when i deployed to IIS 6 on a server.
The ControlMController which has all of the dependenies returns the following exception:
[InvalidOperationException: The IControllerFactory 'SupportTool.web.Controllers.ControllerFactory' did not return a controller for the name 'ControlM'.]
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +304
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +54
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
All of the the other controllers which have 0 dependencies work fine on the server, so the installation of structuremap must be working a little, just not entirely :/

Self answer!
The problem was that the constructor of my datacontext was throwing because the database domain name wasn't fully qualified and while my pc resolved it, the server could not.
The inner exception containing the information wasn't showing on the error page!
:)

Related

Service 'Abp.Quartz.IQuartzScheduleJobManager' which was not registered

I have downloaded .NET Core + Vue template for ASP.NET Boilerplate (v3.7.0).
I added:
code by referencing http://aspnetboilerplate.com/Pages/Documents/Quartz-Integration.
NuGet Abp.Quartz in xxx.Application project.
MyAbpQuartzModule.cs, MyLogJob.cs in xxx.Application project:
[DependsOn(typeof(AbpAutoMapperModule), typeof(AbpQuartzModule))]
public class MyAbpQuartzModule : AbpModule
{
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
}
MyAbpQuartzController.cs in xxx.Web.Host project:
public class MyAbpQuartzController : AbpController
{
private readonly IQuartzScheduleJobManager _jobManager;
public MyAbpQuartzController(IQuartzScheduleJobManager jobManager)
{
_jobManager = jobManager;
}
public async Task<ActionResult> ScheduleJobWithTask()
{
await _jobManager.ScheduleAsync<MyLogJob>(
job =>
{
job.WithIdentity("MyLogJobIdentity", "MyGroup")
.WithDescription("A job to simply write logs.");
},
trigger =>
{
trigger.StartNow()
.WithSimpleSchedule(schedule =>
{
schedule.RepeatForever()
.WithIntervalInSeconds(5)
.Build();
});
});
return Content("OK, scheduled!");
}
public ContentResult TestMyAbpQuartz(string message = "")
{
return Content("OK, scheduled!");
}
}
I debugged the xxx.Web.Host project, but it didn't work.
The http://localhost:21021/MyAbpQuartz/TestMyAbpQuartz page returned:
"This page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500"
I think that QuartzScheduleJobManager didn't register successfully.
So, what should I do?
Part of error message in Web.Host/App_Data/log.txt:
ERROR 2018-06-08 19:19:04,161 [5 ] Mvc.ExceptionHandling.AbpExceptionFilter - Can't create component 'MyNetCoreWithVueProject.Web.Host.Controllers.MyAbpQuartzController' as it has dependencies to be satisfied.
'MyNetCoreWithVueProject.Web.Host.Controllers.MyAbpQuartzController' is waiting for the following dependencies:
- Service 'Abp.Quartz.IQuartzScheduleJobManager' which was not registered.
Castle.MicroKernel.Handlers.HandlerException: Can't create component 'MyNetCoreWithVueProject.Web.Host.Controllers.MyAbpQuartzController' as it has dependencies to be satisfied.
'MyNetCoreWithVueProject.Web.Host.Controllers.MyAbpQuartzController' is waiting for the following dependencies:
- Service 'Abp.Quartz.IQuartzScheduleJobManager' which was not registered.
at Castle.MicroKernel.Handlers.DefaultHandler.AssertNotWaitingForDependency()
at Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden)
at Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired)
at Castle.MicroKernel.DefaultKernel.ResolveComponent(IHandler handler, Type service, IDictionary additionalArguments, IReleasePolicy policy)
at Castle.MicroKernel.DefaultKernel.Castle.MicroKernel.IKernelInternal.Resolve(Type service, IDictionary arguments, IReleasePolicy policy)
at Castle.Windsor.MsDependencyInjection.ScopedWindsorServiceProvider.GetServiceInternal(Type serviceType, Boolean isOptional) in D:\Github\castle-windsor-ms-adapter\src\Castle.Windsor.MsDependencyInjection\ScopedWindsorServiceProvider.cs:line 55
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextExceptionFilterAsync>d__23.MoveNext()
INFO 2018-06-08 19:19:04,967 [5 ] ore.Mvc.Internal.ControllerActionInvoker - Executed action MyNetCoreWithVueProject.Web.Host.Controllers.MyAbpQuartzController.TestMyAbpQuartz (MyNetCoreWithVueProject.Web.Host) in 833.6801ms
ERROR 2018-06-08 19:19:05,059 [5 ] Microsoft.AspNetCore.Server.Kestrel - Connection id "0HLED66DNH26L", Request id "0HLED66DNH26L:00000004": An unhandled exception was thrown by the application.
Castle.MicroKernel.Handlers.HandlerException: Can't create component 'MyNetCoreWithVueProject.Web.Host.Controllers.MyAbpQuartzController' as it has dependencies to be satisfied.
IQuartzScheduleJobManager should be registered by AbpQuartzModule.
I see that you already have [DependsOn(typeof(AbpQuartzModule))] on MyAbpQuartzModule.
Add [DependsOn(typeof(MyAbpQuartzModule))] to *WebHostModule:
[DependsOn(
typeof(AbpProjectNameWebCoreModule),
typeof(MyAbpQuartzModule))]
public class AbpProjectNameWebHostModule : AbpModule
If you want to register a specific class that does not fit into the conventional registration rules. ASP.NET Boilerplate provides the ITransientDependency, the IPerWebRequestDependency and the ISingletonDependency interfaces as a shortcut.
public interface IQuartzScheduleJobManager
{
//...
}
public class QuartzScheduleJobManager: IQuartzScheduleJobManager, ITransientDependency
{
//...
}

ELMAH stylesheet not working with Simple Injector

In an ASP.NET app, when trying to work with both Simple Injector and ELMAH, the following get request returns a 500 error:
GET /elmah.axd/stylesheet returns a 500 error.
The error message:
No registration for type ManifestResourceHandler could be found and an implicit registration could not be made. For the container to be able to create ManifestResourceHandler it should have only one public constructor: it has 2. See https://simpleinjector.org/one-constructor for more information.
Stack trace:
SimpleInjector.ActivationException: No registration for type ManifestResourceHandler could be found and an implicit registration could not be made. For the container to be able to create ManifestResourceHandler it should have only one public constructor: it has 2. See https://simpleinjector.org/one-constructor for more information.
at SimpleInjector.Container.ThrowNotConstructableException(Type concreteType)
at SimpleInjector.Container.ThrowMissingInstanceProducerException(Type serviceType)
at SimpleInjector.Container.ThrowInvalidRegistrationException(Type serviceType, InstanceProducer producer)
at SimpleInjector.Container.GetRegistration(Type serviceType, Boolean throwOnFailure)
at WebApp.Global.InitializeHandler(IHttpHandler handler) in .......\Global.asax.cs:line 63
at WebApp.PageInitializerModule.<>c__DisplayClass1_0.<System.Web.IHttpModule.Init>b__0(Object sender, EventArgs e) in .......\Global.asax.cs:line 48
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Following the "for more information link" mentioned above, there is a further link to some documentation on how to try to fix these types of errors. The link is:
https://simpleinjector.readthedocs.io/en/latest/extensibility.html#overriding-constructor-resolution-behavior
There, 2 fixes are proposed. I tried both fixes, and for each, got the following different errors.
First Fix
Where the GreediestConstructorBehavior is used. This fix yielded the following error message and stack trace:
First Fix Error Message:
No registration for type ManifestResourceHandler could be found and an implicit registration could not be made. The constructor of type ManifestResourceHandler contains parameter 'resourceName' of type String which can not be used for constructor injection.
First Fix Stack Trace:
SimpleInjector.ActivationException: No registration for type ManifestResourceHandler could be found and an implicit registration could not be made. The constructor of type ManifestResourceHandler contains parameter 'resourceName' of type String which can not be used for constructor injection.
at SimpleInjector.Container.ThrowNotConstructableException(Type concreteType)
at SimpleInjector.Container.ThrowMissingInstanceProducerException(Type serviceType)
at SimpleInjector.Container.ThrowInvalidRegistrationException(Type serviceType, InstanceProducer producer)
at SimpleInjector.Container.GetRegistration(Type serviceType, Boolean throwOnFailure)
at WebApp.Global.InitializeHandler(IHttpHandler handler) in .......\Global.asax.cs:line 63
at WebApp.PageInitializerModule.<>c__DisplayClass1_0.<System.Web.IHttpModule.Init>b__0(Object sender, EventArgs e) in .......\Global.asax.cs:line 48
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Second Fix
Where the MostResolvableParametersConstructorResolutionBehavior is used. This second fix yielded the following error message and stack trace:
Second Fix Error Message:
No registration for type ManifestResourceHandler could be found and an implicit registration could not be made. For the container to be able to create ManifestResourceHandler, it should contain a public constructor that only contains parameters that can be resolved.
Second Fix Stack Trace
SimpleInjector.ActivationException: No registration for type ManifestResourceHandler could be found and an implicit registration could not be made. For the container to be able to create ManifestResourceHandler, it should contain a public constructor that only contains parameters that can be resolved.
at SimpleInjector.Container.ThrowNotConstructableException(Type concreteType)
at SimpleInjector.Container.ThrowMissingInstanceProducerException(Type serviceType)
at SimpleInjector.Container.ThrowInvalidRegistrationException(Type serviceType, InstanceProducer producer)
at SimpleInjector.Container.GetRegistration(Type serviceType, Boolean throwOnFailure)
at WebApp.Global.InitializeHandler(IHttpHandler handler) in .......\Global.asax.cs:line 63
at WebApp.PageInitializerModule.<>c__DisplayClass1_0.<System.Web.IHttpModule.Init>b__0(Object sender, EventArgs e) in .......\Global.asax.cs:line 48
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Thanks to anyone who can help out with this.
Fixed by updating the PageInitializerModule class so that Simple Injector ignores the ELMAH handlers:
Before change:
public sealed class PageInitializerModule : IHttpModule
{
public static void Initialize()
{
DynamicModuleUtility.RegisterModule(typeof(PageInitializerModule));
}
void IHttpModule.Init(HttpApplication app)
{
app.PreRequestHandlerExecute += (sender, e) => {
var handler = app.Context.CurrentHandler;
if (handler != null)
{
string name = handler.GetType().Assembly.FullName;
if (!name.StartsWith("System.Web") &&
!name.StartsWith("Microsoft"))
{
Global.InitializeHandler(handler);
}
}
};
}
void IHttpModule.Dispose() { }
}
Changed to:
public sealed class PageInitializerModule : IHttpModule
{
public static void Initialize()
{
DynamicModuleUtility.RegisterModule(typeof(PageInitializerModule));
}
void IHttpModule.Init(HttpApplication app)
{
app.PreRequestHandlerExecute += (sender, e) => {
var handler = app.Context.CurrentHandler;
if (handler != null)
{
string name = handler.GetType().Assembly.FullName;
if (!name.StartsWith("System.Web") &&
!name.StartsWith("Microsoft") &&
!name.StartsWith("Elmah")) // <----- ADDED THIS -----
{
Global.InitializeHandler(handler);
}
}
};
}
void IHttpModule.Dispose() { }
}

Error occurred when trying to create a controller of type 'EmployeeController'. Make sure controller has a parameterless public constructor

Why I'm I getting this error on Employee Controller rest of them are working perfectly
Here is my Employee Controller
public class EmployeeController : ApiController
{
#region Call service
private readonly IEmployeeServices _employeeServices;
public EmployeeController(IEmployeeServices employeeServices)
{
_employeeServices = employeeServices;
}
readonly IEmployeeServices employeeServices = new EmployeeServices();
public EmployeeController():base()
{
_employeeServices = employeeServices;
}
}
AND this is my perfectly Working Product Controller
public class ProductController : ApiController
{
#region Call service
private readonly IProductServices _productServices;
public ProductController(IProductServices productServices)
{
_productServices = productServices;
}
readonly IProductServices productServices = new ProductServices();
public ProductController()
{
_productServices = productServices;
}
}
Here is the stack trace
An error has occurred.An error occurred when trying to create a controller of type 'EmployeeController'. Make sure that the controller has a parameterless public constructor.System.InvalidOperationException at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
 at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)
 at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()An error has occurred.Resolution of the dependency failed, type = "TheWork.Controllers.EmployeeController", name = "(none)".
 Exception occurred while: while resolving.
 Exception is: InvalidOperationException - The current type, BusinessServices.IEmployeeServices, is an interface and cannot be constructed. Are you missing a type mapping?
 -----------------------------------------------
 At the time of the exception, the container was:
 
 Resolving TheWork.Controllers.EmployeeController,(none)
 Resolving parameter "employeeServices" of constructor TheWork.Controllers.EmployeeController(BusinessServices.IEmployeeServices employeeServices)
 Resolving BusinessServices.IEmployeeServices,(none)
 Microsoft.Practices.Unity.ResolutionFailedException at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable1 resolverOverrides)
 at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
 at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, Type t, ResolverOverride[] overrides)
 at Unity.WebApi.UnityDependencyScope.GetService(Type serviceType)
 at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func1& activator)
 at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)An error has occurred.The current type, BusinessServices.IEmployeeServices, is an interface and cannot be constructed. Are you missing a type mapping?System.InvalidOperationException at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForAttemptingToConstructInterface(IBuilderContext context)
 at lambda_method(Closure , IBuilderContext )
 at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
 at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
 at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
 at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
 at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
 at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
 at lambda_method(Closure , IBuilderContext )
 at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
 at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
 at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
 at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
 at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
Update
Here is the Unity Configuration
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
System.Web.Mvc.DependencyResolver.SetResolver(new UnityDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
RegisterTypes(container);
}
public static void RegisterTypes(IUnityContainer container)
{
ComponentLoader.LoadContainer(container, ".\\bin", "TheWork.dll");
ComponentLoader.LoadContainer(container, ".\\bin", "BusinessServices.dll");
ComponentLoader.LoadContainer(container, ".\\bin", "DataModel.dll");
}
}
Buried in the stack trace is the root cause of the issue:
InvalidOperationException - The current type,
BusinessServices.IEmployeeServices, is an interface and cannot be
constructed. Are you missing a type mapping?
----------------------------------------------- At the time of the exception, the container was: Resolving
TheWork.Controllers.EmployeeController,(none) Resolving parameter
"employeeServices" of constructor
TheWork.Controllers.EmployeeController(BusinessServices.IEmployeeServices
employeeServices) Resolving BusinessServices.IEmployeeServices,(none)
Microsoft.Practices.Unity.ResolutionFailedException at
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object
existing, String name, IEnumerable1 resolverOverrides)
The issue is that the EmployeeController requires an instance of IEmployeeServices but Unity does not know what concrete type to instantiate. It looks like the implementation class is supposed to be registered by the call to ComponentLoader.LoadContainer(container, ".\\bin", "BusinessServices.dll"); but for some reason it is not being registered. It could be a bug in that code or perhaps the BusinessServices.dll is out of date and does not contain the IEmployeeServices definition.
It's hard to tell why IEmployeeServices is not registered without seeing all the code and runtime dependencies (because types are being dynamically loaded/registered).
Try this way :)
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IEmployeeServices >().To<EmployeeServices >().InRequestScope();
}

Nancy using Razor view engine: Embedded views don't work

I have the following code:
public class Program : NancyModule
{
static void Main(string[] args)
{
using (var host = new NancyHost(new Uri("http://localhost:444"), new CustomConventionsBootstrapper()))
{
host.Start();
Console.ReadLine();
}
}
public Program()
{
Get["/"] = parameter =>
{
dynamic var = new ExpandoObject();
var.Test = "Lol";
return View["RazorView.cshtml", var];
};
}
}
public class CustomConventionsBootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container);
//This should be the assembly your views are embedded in
var assembly = Assembly.GetEntryAssembly();
ResourceViewLocationProvider.RootNamespaces.Add(assembly, "NancyTest.Views");
}
protected override NancyInternalConfiguration InternalConfiguration
{
get
{
var res = base.InternalConfiguration;
res.ViewLocationProvider = typeof(ResourceViewLocationProvider);
return res;
}
}
void OnConfigurationBuilder(NancyInternalConfiguration x)
{
x.ViewLocationProvider = typeof(ResourceViewLocationProvider);
}
}
And I have RazorView.cshtml in a folder Views in my project set as embedded resource, however each time I open the page it will give me
Nancy.RequestExecutionException: Oh noes! ---> Nancy.ViewEngines.ViewNotFoundException: Unable to locate view 'RazorView.cshtml'
Currently available view engine extensions: sshtml,html,htm,cshtml,vbhtml
Locations inspected: views/Program/RazorView.cshtml-en-GB,views/Program/RazorView.cshtml,Program/RazorView.cshtml-en-GB,Program/RazorView.cshtml,views/RazorView.cshtml-en-GB,views/RazorView.cshtml,RazorView.cshtml-en-GB,RazorView.cshtml
Root path: C:\Users\Student\documents\visual studio 2013\Projects\NancyTest\NancyTest\bin\Debug
If you were expecting raw data back, make sure you set the 'Accept'-header of the request to correct format, for example 'application/json'
bij Nancy.ViewEngines.DefaultViewFactory.GetRenderedView(String viewName, Object model, ViewLocationContext viewLocationContext)
bij Nancy.ViewEngines.DefaultViewFactory.RenderView(String viewName, Object model, ViewLocationContext viewLocationContext)
bij Nancy.Responses.Negotiation.ViewProcessor.Process(MediaRange requestedMediaRange, Object model, NancyContext context)
bij Nancy.Routing.DefaultRouteInvoker.NegotiateResponse(IEnumerable`1 compatibleHeaders, Object model, Negotiator negotiator, NancyContext context)
bij Nancy.Routing.DefaultRouteInvoker.ProcessAsNegotiator(Object routeResult, NancyContext context)
bij Nancy.Routing.DefaultRouteInvoker.InvokeRouteWithStrategy(Object result, NancyContext context)
bij Nancy.Routing.DefaultRouteInvoker.<>c__DisplayClass9.b__5(Task`1 completedTask)
--- Einde van intern uitzonderingsstackpad ---
bij Nancy.NancyEngine.InvokeOnErrorHook(NancyContext context, ErrorPipeline pipeline, Exception ex)
It is worth noting that this only happens when using Razor views. When I use a simple html file it can find those files fine. I even tried to run old example projects found online on the current (0.22.2) Nancy version, but no luck there either. What's going on?
Thanks
Okay figured this out, but I have to say this is kinda stupid. Checked the source, this is the culprit:
ResourceAssemblyProvider.cs line 31
private static IEnumerable<Assembly> GetFilteredAssemblies()
{
return AppDomainAssemblyTypeScanner.Assemblies
.Where(x => !x.IsDynamic)
.Where(x => !x.GetName().Name.StartsWith("Nancy", StringComparison.OrdinalIgnoreCase));
}
My assembly is called 'NancyTest'. Changed to 'TestNancy', works now. I suggest finding a better way of excluding your own assemblies.
Also, when working with embedded views, one can easily forget to add the view as an embedded resource (a common gotcha that took me a while to get used to):
Right click on view-file -> properties -> Build Action -> select "Embedded Resource"

Override CreateTempDataProvider() to solve null reference exception at System.Web.Mvc.Controller.PossiblyLoadTempData()

So I just implemented a base controller on my MVC3 site in order to have some things execute before every view is loaded. Particularly I wanted something that would act as a kind of master page code behind. Once I rolled this and made all my controllers inherit from my base controller I get this error:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Mvc.Controller.PossiblyLoadTempData() +11
System.Web.Mvc.Controller.ExecuteCore() +38
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
I read a few places that you need to override CreateTempDataProvider() and return something or other, but I can't quite figure out the code to do so. I am relatively new with .NET and have yet to override anything before, so I am not sure how to go about this. IF you have run into this before, or know what to do, please help!
Here is my base controller and the attempt at overriding that I have done so far to no avail:
public class BaseController : Controller
{
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
string document = Path.Combine(HttpRuntime.AppDomainAppPath, "quote.xml");
string _quote = "";
string _author = "";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(document);
XmlNode Quote = xmlDoc.SelectSingleNode("quote/text");
XmlNode Author = xmlDoc.SelectSingleNode("quote/author");
_quote = Quote.InnerText;
_author = Author.InnerText;
ViewData["Quote"] = _quote;
}
protected override ITempDataProvider CreateTempDataProvider()
{
return base.CreateTempDataProvider();
}
}
And here is the controller that is trying to run when I start debugging (dunno if you need it):
public class BlogController : BaseController
{
private DarkRobotEntities1 db = new DarkRobotEntities1();
//
// GET: /Blog/
public ViewResult Index()
{
var posts = db.Posts.Include(p => p.Blog).Include(p => p.Comments);
return View(posts.ToList());
}
...
}
You need to call base.Initialize() at the top of your overridden Initialize() method to initialize the base Controller class.
Otherwise, the properties used by PossiblyLoadTempData() will never be set.

Categories