Error when using DependencyResolver for Controller instantiation with MVC 3 - asp.net

I'm using MVC 3 and using the following code when the application starts...
UnityContainer container = new UnityContainer();
new UnityMappings(container);
DependencyResolver.SetResolver(new UnityServiceLocator(container));
Now when the app runs I'm getting the following error (but only sometimes)...
Activation error occured while trying to get instance of type
IControllerFactory, key ""
Interestingly, if I continue with the web request, the website works normally.
Any ideas? I can't see what I'm doing differently from before when this worked fine.
Cheers, Ian.

MVC3 requests a lot more than just controllers from the DependencyResolver. For most of them MVC3 falls back to the default implementation in case the DependencyResolver does not return an instance.
In your case it requests the IControllerFactory which is unknown to your IoC container and it throws an exception which is caught by the UnityServiceLocator implementation and null is returned. MVC then falls back to the default controller factory.
Unlike other IoC containers Unity does not provide an optional TryResolve and therefore does not support a proper exceptionless implementation of the DependencyResolver.

I would suggest first looking through the config and make sure everything is correct there, then I would make sure I had all the assemblies needed for Unity referenced in the project. That error message may (in my experience) point to an error in config or a missing DLL, perhaps an assembly you want to load in the container or another DLL needed by a DLL loaded by Unity?
Hope this helps.

Related

UnityContainerBase.RegisterInstance<Interface> throwing ThreadSynchronizationLock Exception

I am working on a Silverlight application which gets data from WCF service. Once I receive the data from the service I am trying to register an instance of an object to the Unity container and I see that it throws ThreadSynchronizationLock exception.
Can anybody help me avoid this exception?
Known issue. The RegisterInstance method (actually the ContainerControlledLifetimeManager) will try to release a lock it doesn't have when doing RegisterInstance. This is actually a first-chance exception, is properly handled in the codebase, and only shows up in the debugger.
Basically, you don't need to avoid it, it's already handled properly inside the code.
Also, my understanding is that this behavior was changed in Unity 3.0 to avoid exactly these kinds of questions. :-)

ASP.net MVC4 WebAPI JSON Medium Trust

So, I've been playing with ASP.net MVC4 and the new WebAPI the past few days. One of the first things I always do when starting a new app is throw <trust level="Medium" /> into my Web.config so I can be sure my app will run on most hosts.
Usually, if I use the stock Microsoft stuff everything works without a problem. But tonight I was having problems following Brad Wilson's Webstack of Love presentation. All of my AJAX calls were returning a Server 500 error. However, when I would hit the WebAPI directly in the browser, it would return everything in XML format.
So I assume the serialization to JSON withing the WebAPI controller is what is causing the issue. My question is how to work around this?
It bothers me that Microsoft teaches shared hosts to play it safe and lock things down to Medium Trust, then creates new web technology that won't work in Medium Trust. Maybe everything will be fine when it is a final release and the binaries are installed in the GAC? It can take months for shared hosts to upgrade to the latest and greatest.
It seems like the biggest problem is usually Reflection--90%+ of the stuff I've tried that won't run on Medium Trust is due to this (For instance, I'd love to use AutoMapper instead of hand-coding ViewModel => Entity mappings). Is there a way to confine Reflection to the assemblies within an app so it can become part of the Medium Trust feature set and make this problem a thing of the past?
I set up Failed Request Tracing on IIS when I found that the Application_Error event wasn't even firing in my Global.asax. This is the exception being thrown. Not sure how to get any more details.
Warning -MODULE_SET_RESPONSE_ERROR_STATUS
ModuleName ManagedPipelineHandler
Notification 128
HttpStatus 500
HttpReason Internal Server Error
HttpSubStatus 0
ErrorCode 0
ConfigExceptionInfo
Notification EXECUTE_REQUEST_HANDLER
ErrorCode The operation completed successfully. (0x0)
Link to sample project displaying the issue. Also enclosed in the base "Test" directory are screenshots of my fiddler tests: XML-fiddle.png & JSON-fiddle.png.
Web API works just fine in medium trust. Also, since RC version, it 's not deployed to GAC anymore. You can just xcopy Web API dlls onto the server and reference them (or simply just publish your project from VS or git publish it if your host support it, like Azure).
You mention web stack of love. Well, it is SignalR that doesn't work in medium trust mode. See here - according to David Folwer, it won't anytime soon https://github.com/SignalR/SignalR/issues/364
Finally, if you are getting error 500s always add this to Global.asax
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
to receive verbose errors.
My problem had to do with the serializing of Entities with circular relationships (in this case Countries => States, State => Country). The JSON serializer was unable to handle this which led to a 500 error when requesting JSON.
I often use Entities directly for mocking things up and getting a prototype. I always planned on using distinct View Models anyway, but I wanted to understand what was going on and why it was failing.
Kiran Challa's answer in my ASP.net forums question helped me get the error that was occuring: "The RelationshipManager object could not be serialized. This type of object cannot be serialized when the RelationshipManager belongs to an entity object that does not implement IEntityWithRelationships."
That then led me to the Serializing Circular References with JSON.Net and Entity Framework on johnnycode.com.

can't register objects using unity 2.0

I created a web service recently and am using unity to inject my object dependencies. My composition root is the Application_Start in the web services and am using the web.config to do my object to interface mappings. Everything was working fine, however after i loaded my project into tfs i keep getting an error stating that it cant resolve one of the interfaces. I removed the code to register my objects from the web.config and regsistered them in code instead to test and it all works fine. Any ideas what the problem is. Any ideas how i can troubleshoot this problem.
Before TFs :-
UnityContainer uContainer = new UnityContainer();
UnityConfigurationSection Section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
Section.Configure(uContainer, "CentralRepositoryContainer");
Application["uContainer"] = uContainer;
Amended code which works fine :-
UnityContainer uContainer = new UnityContainer();
uContainer.RegisterType<ICentralRepositoryLifeTimehelper, CentralRepositoryLifeTimeHelper>();
uContainer.RegisterType<IJobsHandler, JobsHandler>();
Application["uContainer"] = uContainer;
I don't know the problem, but to troubleshoot print out all the Unity containers registrations and see what's missing/changed.
Use the code sample from Retrieving Container Registration Information

ASP.NET with Unity 2.0

Can anyone help point me to some good resources for working with Unity 2.0 in an ASP.NET that doesn't talk about ASP.NET MVC?!?
We are not using MVC and I am struggling to get Unity to inject dependencies into my pages following the couple of examples I've read (which are all based on David Hayden's work so they are all presenting the same examples and code).
UPDATE
I tried to go the PageHandlerFactory route but the example (here) is incomplete and no source code is available to accompany the article.
So, I decided to try the custom HttpModule approach described here and here. Again, no source code is available beyond what is shown so it is difficult to troubleshoot issues.
The problem I have now is that all of the plumbing appears to be wiring up correctly but the Buildup method does nothing to my page. I can see all of the types are registered in the container when I set a break-point in the module code and the code is executing as expected. But a break-point in the Page_Load event handler shows that the dependencies are all null.
The property in question is public, with a setter and getter, and is marked with the Dependency attribute. I've tried with and without the attribute, with and without a mapping name, ... every combination I could think of and nothing works.
What am I missing???
It depends what you expect. Most exemples targeting MVC present custom controller factory which allows creating controllers with dependency injection. This is indeed also possible with web forms but instead of controller you must inject dependencies into pages. To do this you must replace PageHandlerFactory with custom implementation.
You can create your own implementation of PageHandlerFactory which will be able to resolve pages directly and inject dependencies defined in constructor or you can use one of these (here, here and here) which instead uses stantandard PageHandlerFactory and builds page instance (resolve property dependencies).

Method 'XYZ' cannot be reflected

We have consumed a third party web service and are trying to invoke it from an ASP.NET web application.
However when I instantiate the web service the following System.InvalidOperationException exception is thrown:
Method 'ABC.XYZ' can not be reflected.
System.InvalidOperationException:
Method 'ABC.XYZ' can not be reflected.
---> System.InvalidOperationException: The XML element 'MyDoc' from namespace
'http://mysoftware.com/ns' references
a method and a type. Change the
method's message name using
WebMethodAttribute or change the
type's root element using the
XmlRootAttribute.
From what I can gather there appears to be some ambiguity between a method and a type in the web service.
Can anyone clarify the probably cause of this exception and is there anything I can do to rectify this or should I just go to the web service owners to rectify?
Edit: Visual Studio 2008 has created the proxy class. Unfortunately I can't provide a link to the wsdl as it is a web service for a locally installed thrid party app.
I ran into the same problem earlier today.
The reason was - the class generated by Visual Studio and passed as a parameter into one of the methods did not have a default parameterless constructor. Once I have added it, the error had gone.
It seems the problem is down to data type issues between VS and the web service that was written in Java.
Ultimately it was fixed by manually editing the class and schema files that were created by VS.
I have come across the exact same problem when I was consuming a 3rd party web service. The problem in this instance was that the mustUndertand property in the reference file was looking for a Boolean, whereby the namespace property looked for a string.
By looking through the reference i was able to idenitfy the offending property and simply add "overrides" to the method signature.
Not ideal as any time you update the service you have to do this but I couldn't find any other way around this.
To find the reference file select "all files" from the solution explorer
Hope this helps
I'm guessing the wsdl emitted by or supplied with the service is not in a form that wsdl.exe or serviceutil can understand - can you post the wsdl or link to it?
how are you creating the proxy classes?
Also you might like to try and validate the wsdl against the wsdl schema to check its valid
In my case I was getting a "method cannot be reflected" error due to that fact that in the class being returned by method, I had failed to expose a default parameter-less constructor.
I was working in VB.NET. In my return class I had declared a "New(..)" method that took a couple parameters (because that is how I wanted to use it in my code). But by doing so, I had supressed the default (hidden) parameterless New() constructor that VB adds behind the scenes. Apparently the web service handler requires that a parameterless constructor be available. As soon as I added back into my class a parameterless New() constructor, it all worked fine.
I got the same message but mine was caused by a missing System.Runtime.Serialization.dll since I tried to run a 3.5 application on a machine with only .NET 2.0 installed.
I had the same issue but I found that one of the WebMethod parameters has a member that is of type interface that is why VS could not serialise it. here is the exception when trying to download the disco file
System.InvalidOperationException: Cannot serialize member
'Leopard.JobDespatchParameters.SendingUser'
of type 'Leopard.Interfaces.IUser', see inner exception for more
details. ---> System.NotSupportedException: Cannot serialize member
Leopard.JobDespatchParameters.SendingUser
of type Leopard.Interfaces.IUser because it is an interface.
Old thread but I had a different issue, Maybe of help to someone. referenced dlls were mixed up between two versions on data layer and service layer that caused the problem.
Another scenario where this error can happen: I simply had another web method with the same name (but different parameters)in my web service that slipped in during a code merge. After I deleted the old method it worked.

Resources