I am using ServiceStack in standalone mode. It is now giving a TypeInitialzationException when executing Apphost.Start().
At the time, I was working on implementing some custom filters, but removing the annotation from the only filtered DTO class did not solve the problem.
The stack trace does not show any of my classes involved, and the failing class is the JsvReader which I don't use explicitly.
How can prevent this problem?
Note: I just used nuget to update all packages, so this is current as of now, 3.9.43 for all ServiceStack components.
Exception Detail
System.TypeInitializationException occurred
HResult=-2146233036
Message=The type initializer for 'ServiceStack.Text.Jsv.JsvReader`1' threw an exception.
Source=ServiceStack.Text
TypeName=ServiceStack.Text.Jsv.JsvReader`1
StackTrace:
at ServiceStack.Text.Jsv.JsvReader`1.GetParseFn()
at ServiceStack.Text.Jsv.JsvReader.GetParseFn(Type type)
at ServiceStack.ServiceModel.Serialization.StringMapTypeDeserializer..ctor(Type type)
at ServiceStack.ServiceHost.RestPath..ctor(Type requestType, String path, String verbs, String summary, String notes)
at ServiceStack.ServiceHost.ServiceController.RegisterRestPaths(Type requestType)
at ServiceStack.ServiceHost.ServiceController.RegisterCommon(Type serviceType, Type requestType, Type responseType)
at ServiceStack.ServiceHost.ServiceController.RegisterNService(ITypeFactory serviceFactoryFn, Type serviceType)
at ServiceStack.ServiceHost.ServiceController.Register(ITypeFactory serviceFactoryFn)
at ServiceStack.ServiceHost.ServiceManager.Init()
at ServiceStack.WebHost.Endpoints.Support.HttpListenerBase.Init()
at ArdWebServer.Program.Main(String[] args)
InnerException: System.TypeInitializationException
HResult=-2146233036
Message=The type initializer for 'ServiceStack.Text.Common.DeserializeSpecializedCollections`2' threw an exception.
Source=ServiceStack.Text
TypeName=ServiceStack.Text.Common.DeserializeSpecializedCollections`2
StackTrace:
at ServiceStack.Text.Common.DeserializeSpecializedCollections`2.get_Parse()
at ServiceStack.Text.Common.JsReader`1.GetCoreParseFn[T]()
at ServiceStack.Text.Common.JsReader`1.GetParseFn[T]()
at ServiceStack.Text.Jsv.JsvReader`1..cctor()
InnerException: System.NullReferenceException
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=ServiceStack.Text
StackTrace:
at ServiceStack.Text.PlatformExtensions.GenericTypeArguments(Type type)
at ServiceStack.Text.Common.DeserializeSpecializedCollections`2.GetGenericEnumerableParseFn()
at ServiceStack.Text.Common.DeserializeSpecializedCollections`2.GetParseFn()
at ServiceStack.Text.Common.DeserializeSpecializedCollections`2..cctor()
InnerException:
My App host
public class AppHost : AppHostHttpListenerBase
{
public AppHost() : base("IAM Tools Service Stack Host", typeof (Tims.Global).Assembly)
{
CatchAllHandlers.Add(
(httpMethod, pathInfo, filePath) =>
Tims.Support.StaticFileHandler.Factory(
Params.Instance.HttpDataDir,
"/",
pathInfo
)
);
}
public override void Configure(Funq.Container container)
{
SetConfig(new EndpointHostConfig()
{
DebugMode = true,
WriteErrorsToResponse = true
});
}
}
Related
I am registering my interface in App.config. But while resolving, I am getting the below exception.
Microsoft.Practices.Unity.ResolutionFailedException
HResult=0x80131500
Message=Resolution of the dependency failed, type = "Philips.DI.Interfaces.UW.DtoModel.IModelProvider`1[Philips.DI.UW.PatientOrchestrator.Interfaces.PatientScheduleDataModel]", name = "LoginPage".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, Philips.DI.Interfaces.UW.DtoModel.IModelProvider`1[Philips.DI.UW.PatientOrchestrator.Interfaces.PatientScheduleDataModel], is an interface and cannot be constructed. Are you missing a type mapping?
At the time of the exception, the container was:
Resolving Philips.DI.Interfaces.UW.DtoModel.IModelProvider`1[Philips.DI.UW.PatientOrchestrator.Interfaces.PatientScheduleDataModel],LoginPage
var proxy = container.Resolve<T>("LoginPage", new ResolverOverride[] {
new ParameterOverride("unityContainer", container),new ParameterOverride("serviceEndPoint", serviceEndPoint)});
public SyncProxy(IUnityContainer unityContainer, ServiceEndPoint serviceEndPoint) : base(unityContainer, serviceEndPoint)
{
_clientDataSyncWrapper = unityContainer.Resolve<ClientDataSyncWrapper>();
RegisterPushMessages();
}
[InjectionConstructor]
public SyncProxy(IUnityContainer unityContainer, string endPoint) : base(unityContainer, endPoint)
{
_clientDataSyncWrapper = unityContainer.Resolve<ClientDataSyncWrapper>();
RegisterPushMessages();
}
I'm following below example to create a class instance at runtime using autofac.
http://autofaccn.readthedocs.io/en/latest/advanced/delegate-factories.html
But when running locally, I'm seeing an exception. I'm very new to autofac and let me know if I'm doing anything wrong here or if you need any more information.
Code structure:
public class ClassName
{
public delegate ClassName Factory(Type1 obj1, string obj2);
public ClassName(Type1 obj1, string obj2)
{
this.type1 = obj1;
this.type2= obj2;
}
/*Some methods of this class that use type1 and type2*/
}
// Registration
container.RegisterType<Type1>();
container.RegisterType<ClassName.Factory>();
container.RegisterType<ClassName>().AsSelf().InstancePerDependency();
// In some method to create an instance of ClassName
var factory = container.Resolve<Factory>(); // This is throwing the following exception.
var instance = factory(obj1Instance, "text"); // obj1Instance and "text" parameters cannot be determined at registration time.
The exception stackTrace:
Logging handled exception: Autofac.Core.DependencyResolutionException: Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = Factory (ReflectionActivator), Services = [ClassName+Factory], Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime, Sharing = None, Ownership = OwnedByLifetimeScope ---> None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'ClassName+Factory' can be invoked with the available services and parameters:
Cannot resolve parameter 'System.Object object' of constructor 'Void .ctor(System.Object, IntPtr)'. (See inner exception for details.) ---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'ClassName+Factory' can be invoked with the available services and parameters:
Cannot resolve parameter 'System.Object object' of constructor 'Void .ctor(System.Object, IntPtr)'.
at Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext context, IEnumerable`1 parameters)
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
--- End of inner exception stack trace ---
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Execute()
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)
at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable`1 parameters)
The problem you have is that you're trying to register a factory.
Autofac understands how to resolve a delegate, but it doesn't understand how to register it.
This should work:
public class ClassName
{
public delegate ClassName Factory(Type1 obj1, string obj2);
public ClassName(Type1 obj1, string obj2)
{
this.type1 = obj1;
this.type2= obj2;
}
}
// Registration
container.RegisterType<ClassName>().AsSelf().InstancePerDependency();
// In some method to create an instance of ClassName
var factory = container.Resolve<ClassName.Factory>();
var instance = factory.Invoke(obj1Instance, "text");
Edit:
After running this myself I got the same exception but quickly realised what the issue was. Quoting autofac's entry on delegate factories I saw this:
By default, Autofac matches the parameters of the delegate to the parameters of the constructor by name
The names of my constructor's parameters and my delegates' parameters didn't match which leads autofac to try and resolve the object by type, and since you haven't (and shouldn't unless you know you want to, and even so, you shouldn't) registered a string autofac's Autofac.Core.Activators.Reflection.DefaultConstructorFinder fails.
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();
}
I got an error on the creation of an api controller due to that I didn't set up autofac for webapi.
However, I can't seem to catch the exception anywhere.
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'MyWeb.Web.Controllers.MyController' does not have a default constructor
</ExceptionMessage>
<ExceptionType>System.ArgumentException</ExceptionType>
<StackTrace>
at System.Linq.Expressions.Expression.New(Type type) at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
</StackTrace>
</Error>
I tried adding WebApi contrib for Elmah, then I added this:
config.Filters.Add(new Elmah.Contrib.WebApi.ElmahHandleErrorApiAttribute());
Didn't make elmah register the exception.
I added the following to global.asax:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}
Didn't make any difference at all.
How can I handle errors happening before the controllers are called?
I wonder if this exception is just being added to the content of the HttpResponseMessage but is not actually being thrown as an exception. When implementing a dependency resolver class for use during constructor instantiation, it usually makes sense to attempt resolution, catch exceptions and return null.
For example, in non-API MVC controllers I've often used something like this:
public class UnityDependencyResolver : IDependencyResolver
{
public readonly IUnityContainer Container;
public UnityDependencyResolver(IUnityContainer container)
{
Container = container;
}
#region IDependencyResolver Members
public object GetService(Type serviceType)
{
try
{
return Container.Resolve(serviceType);
}
catch (Exception ex)
{
if (ex.InnerException is TypeInitializationException)
throw ex.InnerException;
return null;
}
}
...
I am receiving a FaultException from a WCF service as follows when it is invoked:
2012-04-02 16:26:00.3593|Error|System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]: The type initializer for 'vService.CheckService' threw an exception. (Fault Detail is equal to An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.TypeInitializationException: The type initializer for 'vService.CheckService' threw an exception. ----> System.NullReferenceException: Object reference not set to an instance of an object.
at vService.CheckService..cctor() in d:\working\code\VioletServer\vService\CheckService.cs:line 14
--- End of inner ExceptionDetail stack trace ---
at vService.CheckService..ctor()
at CreatevService.CheckService()
at System.ServiceModel.Dispatcher.InstanceProvider.GetInstance(InstanceContext instanceContext, Message message)
at System.ServiceModel.Dispatcher.InstanceBehavior.GetInstance(InstanceContext instanceContext, Message request)
at System.ServiceModel.InstanceContext.GetServiceInstance(Message message)
at System.ServiceModel.Dispatcher.InstanceBehavior.EnsureServiceInstance(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)
...).
Line 14 of CheckService.cs is
private static string connStr = ConfigurationManager.ConnectionStrings["violetdb"].ConnectionString;
What does the exception mean in this context and how can I resolve it?
//CheckService.cs
public class CheckService : ICheckService
{
private static string connStr = ConfigurationManager.ConnectionStrings["violetdb"].ConnectionString;
MessageRepository _repo = new MessageRepository(connStr);
public CheckService(){}
public CheckService(MessageRepository repo)
{
_repo = repo;
}
public void SendMessage(string sender, string recipient, string messagetext)
{
_repo.DeliverMessage(sender,recipient,messagetext);
}
}
Most likely your WCF service does not have a connection string named "violetdb" in its application configuration file.
A TypeInitializerException is thrown in this circumstance, because you have a static field which is being initialised ahead of type construction, and because the ConnectionStrings["violetdb"] call is returning null, and it is throwing an NullReferenceException.
Bottom line, check the <connectionStrings> section of your configuration file and ensure that the connection string exists.