I have gotten myself into an interesting situation, and i am confused since i think i am doing all the right stuff here... I am getting the following error:
The current type, Services.Interfaces.IKenticoService, is an interface and cannot be constructed. Are you missing a type mapping?
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.InvalidOperationException: The current type, Services.Interfaces.IKenticoService, is an interface and cannot be constructed. Are you missing a type mapping?
Source Error:
Line 113: throw new InvalidOperationException("Container on Global Application Class is Null. Cannot perform BuildUp.");
Line 114:
Line 115: container.BuildUp(this as T);
Line 116: }
Line 117:
Source File: c:\PROJECTS\CMS\CurentSprint\currentsprint\Source\WebProject\App_Code\Global\BasePage.cs Line: 115
and the error is generated by base page:
protected override void OnPreInit(EventArgs e)
{
InjectDependencies();
base.OnPreInit(e);
}
/// <summary>
/// This method is used to inject any controller related dependencies from
/// our existing web page.
/// </summary>
protected virtual void InjectDependencies()
{
HttpContext context = HttpContext.Current;
if (context == null)
return;
IContainerAccessor accessor = context.ApplicationInstance as IContainerAccessor;
if (accessor == null)
return;
IUnityContainer container = accessor.Container;
if (container == null)
throw new InvalidOperationException("Container on Global Application Class is Null. Cannot perform BuildUp.");
container.BuildUp(this as T);
}
I have the mappings in place:
namespace Core.DI
{
public static class UnityHelper
{
public static void ConfigureContainer(IUnityContainer container)
{
container.RegisterType<IPersonRegistrationService, PersonRegistrationService>();
container.RegisterType<ILoginService, LoginService>();
container.RegisterType<IKenticoCMSOfferService, KenticoCMSOfferService>();
container.RegisterType<IKenticoService, KenticoService>();
and then i have some other...
}
}
}
This method is called in side global Application Start method:
public void Application_Start(object sender, EventArgs e)
{
// Azure Application start init
AzureInit.Current.ApplicationStartInit();
CMSAppBase.CMSApplicationStart();
//CustomCode: Added for DI (Unity block)
try
{
//CustomCode: Create the unity container.
Container = new UnityContainer();
UnityHelper.ConfigureContainer(Container);
//mappings
EntityMapper.MapEntities();
}
catch (Exception ex)
{
//TODO: add call to error logger.
}
}
My KenticoService class is setup properly as well:
namespace BusinessLogic.Services
{
public class KenticoService : IKenticoService
{
#region User API Calls
public void HandleCmsUser(Person person, string userName)
{
...
}
public void HandleCmsUser(Person person, string userName, string oldUserName)
{
...
}
#endregion
}
}
Now the kentico service methods are called inside LoginService and PersonRegistrationService only. So in both the classes i have:
[Dependency]
public IKenticoService KenticoServiceInstance { get; set; }
Now we have two sites, our custom MVC solution and a CMS site. The services referenced above are in the projects that are inside our MVC solution. For CMS use, we copy the dlls over to the CMS solution. The MVC solution compiles and runs great. The CMS site is throwing this error and i have double checked that the correct dlls are being referenced here. Are you seeing something here that i may be missing?
Related
I separated the Data Access Layer in my project to apply the different validations rules by countries.
For example i have an interface "IVoucherService"
public interface IVoucherService
{
void Foo();
}
which implement in many Project
namespace VoucherHU
{
[ApiLocalization(ApiLocalization.HU)]
public class VoucherService : IVoucherService
{
public void Foo(){}
}
}
namespace Voucher
{
[ApiLocalization(ApiLocalization.US)]
[ApiLocalization(ApiLocalization.DEFAULT)]
public class VoucherService : IVoucherService
{
public void Foo(){}
}
}
The following code determine which class has to be used
private static Type GetServiceImplementedType<TService>() where TService : class
{
Type serviceType = typeof(TService);
IEnumerable<Type> types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes()).Where(p => !p.IsInterface && serviceType.IsAssignableFrom(p));
Type serviceImplementedClass = null;
foreach (Type type in types)
{
ApiLocalizationAttribute[] attributes = (ApiLocalizationAttribute[])type.GetCustomAttributes(typeof(ApiLocalizationAttribute), true);
if (attributes != null && attributes.Count() > 0 && attributes.Any(a => a.Localization == Localization))
{
serviceImplementedClass = type;
break;
}
}
return serviceImplementedClass;
}
I register these services in the Global.asax -> Application_Start method.
After publish it works fine, the services starts correctly, but if nobody use the website, the IIS (maybe to save resource) pauses the service until the next request. When the API try to re register the services it could not find any class which implements the IVoucherService interface.
I checked it manually in the watch and i got the following error
Services.Voucher.VoucherService error CS0234: The type or namespace
name 'Services' does not exist in the namespace (are you missing an
assembly reference?)
and i got the same error for the other classes which implements this interface.
Any idea why i loose the refference to these files (Services.dll, ServicesHU.dll)?
I figured it out.
Somehow the AppComaing.CurrentDomain.GetAssemblies()no longer contains the assemly informations of the DLL files.
The solution was to refresh the referrenced assemblies on each time when Global.asax -> Application_Start method called.
To refresh the referrenced assemblies use this method
System.Web.Compilation.BuildManager.GetReferencedAssemblies();
I am coding an MVC 5 internet application, and I have a question in regards to handling exceptions globally.
I have my Application_Error setup in my global.asax file. This caters to errors such as 404 HttpExceptions.
How can I send all errors that occur in a controller to the Application_Error function? An example is the following exception:
System.Web.HttpRequestValidationException: A potentially dangerous
Request.Form value was detected from the client (name="").
I have written a OnException(ExceptionContext filterContext) for my controller, but am not sure on how to get the Application_Error function to handle these errors. Do I need to pass the exception from the OnException function, or is this the wrong approach?
Thanks in advance.
You can create a global filter by adding the following class to your App_Start folder:-
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
HandleErrorAttribute can be replaced with your own custom Exception Filter.
All you then need to do is make sure you add the following line of code to the App_Start method of your Gloabal.asax :-
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//AreaRegistration.RegisterAllAreas();
//RouteConfig.RegisterRoutes(RouteTable.Routes);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
}
Hope this helps.
I'm using some kind of http-module which gives me exactly what you are asking for:
public class MyModule : IHttpModule {
public void Init(HttpApplication context) {
context.Error += OnRequestError;
}
private void OnRequestError(object sender, EventArgs e) {
var context = ((HttpApplication)sender).Context;
var error = context.Error;
if (error == null)
return;
var errorType = error.GetType();
if (errorType == typeof(HttpException))
// do something
// this is what you are looking for
if (errorType = typeof(HttpRequestValidationException))
// do something, whatever you want
// works for me, so should work to you too
}
}
To get the module to work, you can use web.config or DynamicModuleHelper:
Install Microsoft.Web.Infrastructure and WebActivatorEx via nuget
Add a Bootstrapper class to your project
Register module at PreApplicationStartMethod
Sample:
// File: Bootstrapper.cs (contains class Bootstrapper)
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using WebActivatorEx;
using WhatEver.It.Is;
[assembly: PreApplicationStartMethod(typeof(Bootstrapper), "Bootstrap")]
namespace WhatEver.It.Is {
public class Bootstrapper {
public static void Bootstrap() {
// Do what do you need just before the application get started
// like registering modules, etc...
DynamicModuleUtility.RegisterModule(typeof(MyModule));
}
}
}
I am seeing an issue in using of unity in controller constructor. Here are the details -
In unit configuration (unity.config)– here is what I am doing –
container.RegisterType<ISessionWrapper, SessionWrapper>()
In the Controller constructor
public OnboardingController( ISessionWrapper sessionwrapper )
{
SessionWrapper = sessionwrapper;
}
SessionWrapper
public interface ISessionWrapper
{
string Brand { get; set; }
//string CurrenSessionCulture { get; set; }
}
public class SessionWrapper : ISessionWrapper
{
public string Brand
{
get;
set;
}
}
Error occuring in doing this
No parameterless constructor defined for this object.
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.MissingMethodException: No parameterless constructor defined for this object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.****
When I change the Controller Constructor definition like this it is all working fine.
public OnboardingController()
: this(new SessionWrapper())
{
//
}
You need to use a custom ControllerFactory using Unity to resolve instances of your controller classes. The default ControllerFactory used by MVC requires that the controller classes have a parameterless constructor.
A custom ControllerFactory using Unity looks like
public class UnityControllerFactory : DefaultControllerFactory {
private readonly IUnityContainer _container;
public UnityControllerFactory (IUnityContainer container) {
_container = container;
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) {
if (controllerType != null) {
return _container.Resolve(controllerType) as IController;
}
else {
return base.GetControllerInstance(requestContext, controllerType);
}
}
}
On application start (normally in the global.asax) you register your ControllerFactory in the MVC Runtime using the following code
var container = // initialize your unity container
var factory = new UnityControllerFactory(container);
ControllerBuilder.Current.SetControllerFactory(factory);
I'm migrating an application from Ninject to Autofac.
We used a special naming convention for injecting app settings into constructors:
public class Example{
public Example(AppSetting settingName){
...
}
}
AppSetting parameter was injected automatically using ConfigurationManager.AppSettings["settingName"].
In Ninject this was accomplished by using a custom provider:
public class AppSettingProvider : Ninject.Activation.IProvider
{
public object Create(IContext context)
{
var varName = ((Context)context).Request.Target.Name;
var value = new AppSetting(ConfigurationManager.AppSettings[varName]);
if (value.Value == null)
{
... log ...
}
return value;
}
public Type Type
{
get { return typeof(AppSetting); }
}
}
I was not able to find an alternative for this feature in Autofac. If this is not possible in an automated way I'm ok with looping over all app settings during the initial configuration step.
Any idea what to do?
Thanks,
Vilem
I have created a solution using this SO question:
Register string value for concrete name of parameter
and subsequently improved it using Travis Illig's suggestion.
Currently this seems to work exactly the same as the Ninject equivalent.
Here's the result:
public class AppSettingsModule : Module
{
protected override void AttachToComponentRegistration(
IComponentRegistry componentRegistry,
IComponentRegistration registration)
{
// Any time a component is resolved, it goes through Preparing
registration.Preparing += InjectAppSettingParameters;
}
private void InjectAppSettingParameters(object sender, PreparingEventArgs e)
{
// check if parameter is of type AppSetting and if it is return AppSetting using the parameter name
var appSettingParameter = new ResolvedParameter((par, ctx) => par.ParameterType == typeof(AppSetting), (par, ctx) => new AppSetting(ConfigurationManager.AppSettings[par.Name]));
e.Parameters = e.Parameters.Union(new List<Parameter>{ appSettingParameter});
}
}
I am using servicestack and having problems with auto wiring.
Error trying to resolve Service '{Service}' or one of its autowired dependencies (see inner exception for details)
I don't need help figuring how exactly what the problem is. What I actually want is a way to see the inner exception. The inner exception should tell me the except problem without me having to figure it out but it not displayed in either the exception returned, or in the logs.
Setting DebugMode doesn't help either, it just includes the stack track of the topmost exception.
So basically, how do I stop servicestack from hiding the inner exception details?
I ran into this same issue and it ended up being that there was an exception being thrown inside of the constructor that I had created for the particular endpoint class. Example...
public class PartnerService : Service
{
private PartnerManagementService _partnerManagementService;
public PartnerService()
{
var configuration = new Configuration();
_partnerManagementService = new PartnerManagementService(configuration);
}
public object Get(PartnerGet partner)
{
try
{
var partners = _partnerManagementService.getPartners();
if (!partners.Any())
{
return new HttpError(HttpStatusCode.NotFound, "Partners Could not be found");
}
return partners;
}
catch (Exception e)
{
return new HttpError(HttpStatusCode.InternalServerError, e);
}
}
If it so happens that an exception is thrown inside of the constructor, ServiceStack will not be able to resolve the service or one of its dependencies, in this case that dependency being the constructor for the class.
If you put a try/catch in the constructor for the class you could get an exception that actually makes sense.
ServiceStack should already return the inner Exception, i.e. here's the source of the error:
private Exception CreateResolveException<TService>(Exception ex)
{
var errMsg = "Error trying to resolve Service '{0}' or one of its autowired dependencies (see inner exception for details).".Fmt(typeof(TService).FullName);
return new Exception(errMsg, ex);
}
Basically there was a problem with your IOC configuration and that one of the dependencies caused an error.
You can change ServiceStack to serialize the Inner Exception with:
SetConfig(new EndpointHostConfig {
ReturnsInnerException = true,
});
But this already defaults to true.
So the exception should already contain the Inner Exception, are you referring to what Exception gets serialized or the exception thrown in code?
One option could be to grab the actual source code from Github and add it as a project to your solution, as opposed to using a compiled DLL, then you could step through the actual code and see exactly where the exception is raised and why.
I have exactly the same exception.
In my case, it happens once migrated to ServiceStack v4. With v3, all works perfectly.
IoC configuration
public class AppHost : AppHostBase
{
public AppHost() : base("Northwind web services", typeof(CustomersService).Assembly)
{ }
public override void Configure( Container container )
{
SetConfig(new HostConfig
{
DebugMode = true,
ReturnsInnerException = true,
});
var dbFactory = new OrmLiteConnectionFactory("~/Northwind.sqlite".MapHostAbsolutePath(), SqliteDialect.Provider);
container.Register(dbFactory);
// Dependencies
container.RegisterAs<CustomerEntityRepository, ICustomerEntityRepository>();
container.RegisterAutoWired<CustomersService>();
}
}
Base class
public abstract class Repository<TEntity> : IRepository<TEntity> where TEntity : IEntity, new()
{
protected IDbConnectionFactory dbFactory { get; set; }
public Repository( IDbConnectionFactory factory )
{
dbFactory = factory;
}
}
Inherited class
public class CustomerEntityRepository : Repository<CustomerEntity>, ICustomerEntityRepository
{
public CustomerEntityRepository( IDbConnectionFactory dbFactory )
: base(dbFactory)
{
}
}
}
Only solution I've found is:
container.RegisterAs<ICustomerEntityRepository>(c => new CustomerEntityRepository(dbFactury));
Here's full exception message returned http://pastebin.com/jJntNN5p