ELMAH stylesheet not working with Simple Injector - c#

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

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
{
//...
}

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

Autofac.Core.Registration.ComponentNotRegisteredException

Im trying to implement CQRS pattern to my app. So I found how to register all command handlers from assembly here : Autofac resolve dependency in CQRS CommandDispatcher
But it doesnt work well for me. Here is the code:
containerBuilder.RegisterAssemblyTypes(assembly)
.AsClosedTypesOf(typeof(ICommandHandler<>));
containerBuilder.RegisterAssemblyTypes(assembly)
.AsClosedTypesOf(typeof(IQueryHandler<,>));
Handlers factory
public class CqrsHandlerFactory : ICqrsHandlerFactory
{
private readonly IContainer container;
public CqrsHandlerFactory(IContainer container)
{
this.container = container;
}
public ICommandHandler<TCommand> GetCommandHandler<TCommand>(TCommand command) where TCommand : class, ICommand
{
return container.Resolve<ICommandHandler<TCommand>>();
}
public IQueryHandler<TQuery, object> GetQueryHandler<TQuery>(TQuery query) where TQuery : class, IQuery
{
return container.Resolve<IQueryHandler<TQuery, object>>();
}
}
Bus
public class CqrsBus : ICqrsBus
{
private readonly ICqrsHandlerFactory cqrsHandlerFactory;
public CqrsBus(ICqrsHandlerFactory cqrsHandlerFactory)
{
this.cqrsHandlerFactory = cqrsHandlerFactory;
}
public void ExecuteCommand(ICommand command)
{
var handler = cqrsHandlerFactory.GetCommandHandler(command);
if (handler == null)
throw new NotImplementedHandlerException(string.Format("Cannot find handler for {0}", command.GetType()));
handler.Handle(command);
}
public TResult RunQuery<TResult>(IQuery query)
{
var handler = cqrsHandlerFactory.GetQueryHandler(query);
if (handler == null)
throw new NotImplementedHandlerException(string.Format("Cannot find handler for {0}", query.GetType()));
return (TResult)handler.Handle(query);
}
}
Exception
An exception of type 'Autofac.Core.Registration.ComponentNotRegisteredException' occurred in Autofac.dll but was not handled in user code
Additional information: The requested service 'PromocjeWsieciowkach.Messaging.Core.ICommandHandler`1[[PromocjeWsieciowkach.Messaging.Core.ICommand, PromocjeWsieciowkach.Messaging.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
Stacktrace
at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable1 parameters)
at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable1 parameters)
at PromocjeWsieciowkach.Messaging.Factories.CqrsHandlerFactory.GetCommandHandler[TCommand](TCommand command) in C:\Users\Daniel\Desktop\PromocjeWsieciowkach\src\PromocjeWsieciowkach.Messaging\Factories\CqrsHandlersFactory.cs:line 17
at PromocjeWsieciowkach.Messaging.Bus.CqrsBus.ExecuteCommand(ICommand command) in C:\Users\Daniel\Desktop\PromocjeWsieciowkach\src\PromocjeWsieciowkach.Messaging\Bus\CqrsBus.cs:line 17
at PromocjeWsieciowkach.Controllers.PostController.Index() in C:\Users\Daniel\Desktop\PromocjeWsieciowkach\src\PromocjeWsieciowkach\Controllers\PostController.cs:line 20
at lambda_method(Closure , Object , Object[] )
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__28.MoveNext()
So what i'am doing wrong?
Your code and the exception message clearly show the problem. In summary, your exception message explains that:
The requested service 'ICommandHandler<ICommand>' has not been registered.
In other words, you are requesting an ICommandHandler<ICommand> instead of an ICommandHandler<TestCommand>. This can be seen here:
public void ExecuteCommand(ICommand command)
{
var handler = cqrsHandlerFactory.GetCommandHandler(command);
// ...
}
The C# compiler applied type inference to the GetCommandHandler<T> call. So the following code is the actual call:
var handler = cqrsHandlerFactory.GetCommandHandler<ICommand>(command);
You should change the ICrqsBus.ExecuteCommand method to the following:
public void ExecuteCommand<TCommand>(TCommand command)
{
// You can merge the factory and your CqrsBus. Splitting them is useless.
var handler = cqrsHandlerFactory.GetCommandHandler<TCommand>();
// You don't need then null check; Autofac never returns null.
handler.Handle(command);
}
If you can't make the ExecuteCommand method generic (e.g. because you don't know the command type at compile time), you should build the generic types using the reflection API as follows:
public class CqrsBus : ICqrsBus
{
private readonly IComponentContext context;
public CqrsBus(IComponentContext context)
{
this.context = context;
}
public void ExecuteCommand(ICommand command)
{
Type handlerType = typeof(ICommandHandler<>).MakeGenericType(command.GetType());
dynamic handler = this.context.Resolve(handlerType);
void handler.Execute((dynamic)command);
}
}
It's also worth noting that if your using nopcommerce and adding a service, the same error is generated if you forget to add your service in the dependancy registrar.
builder.RegisterType<YourService>().As<IYourService>().InstancePerLifetimeScope();
Just came across this myself, and the following quote:
The requested service 'ICommandHandler' has not been registered."
Made me realise about the dependancy registrar.
Thanks Steven

Web Service Throwing Error

I cannot figure this one out. This code has executed flawlessly for quite a while, now out of nowhere it fails. The web service it calls hasn't changed and I am kind of at a loss. The specific error is {"Configuration system failed to initialize"}
Code I'm using:
webservices.WebService ws = new webservices.WebService();
Code in the designer:
namespace NumberOneService.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.WebServiceUrl)]
[global::System.Configuration.DefaultSettingValueAttribute("http://www.webserver.services/ws_partlookup.cfc")]
public string Web_Service {
get {
return ((string)(this["Web_Service"]));
}
}
}
stack trace:
at System.Configuration.ClientConfigurationSystem.OnConfigRemoved(Object sender, InternalConfigEventArgs e)
at System.Configuration.Internal.InternalConfigRoot.RemoveConfigImpl(String configPath, BaseConfigurationRecord configRecord)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.Configuration.ClientSettingsStore.ReadSettings(String sectionName, Boolean isUserScoped)
at System.Configuration.LocalFileSettingsProvider.GetPropertyValues(SettingsContext context, SettingsPropertyCollection properties)
at System.Configuration.SettingsBase.GetPropertiesFromProvider(SettingsProvider provider)
at System.Configuration.SettingsBase.GetPropertyValueByName(String propertyName)
at System.Configuration.SettingsBase.get_Item(String propertyName)
at System.Configuration.ApplicationSettingsBase.GetPropertyValue(String propertyName)
at System.Configuration.ApplicationSettingsBase.get_Item(String propertyName)
at NumberOneService.Properties.Settings.get_Web_Service() in Number One Service\Properties\Settings.Designer.cs:line 33
at NumberOneService.webservices.WebService..ctor() in Number One Service\Web References\webservices\Reference.cs:line 46
at NumberOneService.NumberOneService.bwExecuteProcess_DoWork(Object sender, DoWorkEventArgs e) in Number One Service.cs:line 400
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
This typically happens if you created a web service reference in a class library and then ported it over to a console app or a windows app. the web service references are stored in the settings files with a specific path.
Basically, you're missing a section declaration OR the right setting name in the config file.
please check your config files for the key which stores the url of the service. Else, paste it here and we can help further.
the exception is thrown in the web service constructor when it tries to set the Url from the config file. (host config or settings file)

asp mvc 2 structure map not working when deployed

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!
:)

Categories