Unity 3.5 not resolving controllers - asp.net-mvc-5

I have taken the following example code from the Unity documentation, and yet a basic controller can't be instantiated with a service implementation as a required constructor dependency.
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterTypes(
AllClasses.FromLoadedAssemblies(),
WithMappings.FromMatchingInterface,
WithName.TypeName,
WithLifetime.ContainerControlled);
}
This gives the error Exception information:
Exception type: ResolutionFailedException Exception message:
Resolution of the dependency failed, type =
"[XXX].Controllers.HomeController", name = "(none)". Exception
occurred while: Calling constructor
Microsoft.Practices.Unity.InterceptionExtension.PolicyInjectionBehavior(Microsoft.Practices.Unity.InterceptionExtension.CurrentInterceptionRequest
interceptionRequest,
Microsoft.Practices.Unity.InterceptionExtension.InjectionPolicy[]
policies, Microsoft.Practices.Unity.IUnityContainer container).
Exception is: ArgumentException - Type passed must be an interface
This is an MVC5 application and i have the latest Nuget packages for Unity and the bootstrapper

in order to get this working we switched the WithName parameter to use Default as the passed value.

Related

Azure Functions - Application Insights - Custom Telemetry - EventSource instance already exists

I am trying to follow the instructions in Insights Preview where I can create custom telemetry. I followed the instructions exactly. But maybe I've got it configured wrong.
I have the APPINSIGHTS_INSTRUMENTATIONKEY set in the local.settings.json file and it seems to work fine. But when I add a new TelemetryClient I start getting those duplicate errors (below). It happens when the function gets invoked.
I really would like the telemetry data from AF to go to the same AI instrumentation key so I can see it together.
I also pulled the Microsoft.Extensions.Logging out as I wanted to use AI only, if that makes any difference.
Anyone have any suggestions?
See below...
TIA
ERROR: Exception in Command Processing for EventSource Microsoft-ApplicationInsights-Core: An instance of EventSource with Guid 74af9f20-af6a-5582-9382-f21f674fb271 already exists.
ERROR: Exception in Command Processing for EventSource Microsoft-ApplicationInsights-Core: An instance of EventSource with Guid 74af9f20-af6a-5582-9382-f21f674fb271 already exists.
Microsoft.WindowsAzure.ServiceRuntime Critical: 102 : Unexpcted Exception During Runtime Startup:
System.TypeInitializationException: The type initializer for '<Module>' threw an exception. ---> <CrtImplementationDetails>.ModuleLoadException: The C++ module failed to load while attempting to initialize the default appdomain.
---> System.Runtime.InteropServices.COMException: Invalid operation. (Exception from HRESULT: 0x80131022)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at <CrtImplementationDetails>.GetDefaultDomain()
at <CrtImplementationDetails>.DoCallBackInDefaultDomain(IntPtr function, Void* cookie)
at <CrtImplementationDetails>.LanguageSupport.InitializeDefaultAppDomain(LanguageSupport* )
at <CrtImplementationDetails>.LanguageSupport._Initialize(LanguageSupport* )
at <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* )
--- End of inner exception stack trace ---
at <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* )
at .cctor()
--- End of inner exception stack trace ---
at Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.InitializeEnvironment()
at Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment..cctor()
ERROR: Exception in Command Processing for EventSource Microsoft-ApplicationInsights-Data: An instance of EventSource with Guid a62adddb-6b4b-519d-7ba1-f983d81623e0 already exists.
I started over with a fresh AF project (and a glass of wine) to keep it simple.
The following code works:
private static TelemetryConfiguration config = new TelemetryConfiguration { InstrumentationKey = System.Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY", EnvironmentVariableTarget.Process)};
private static TelemetryClient telemetryClient = new TelemetryClient(config);
This code (directly from the Preview post) does not:
private static TelemetryClient telemetryClient = new TelemetryClient();
private static string key = TelemetryConfiguration.Active.InstrumentationKey = System.Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY", EnvironmentVariableTarget.Process);
An unfortunate side effect is that the telemetry doesn't show up in te VS2017 Application Insights window automatically. You have to use the settings gear to select the AI repository you want and then you can see it. Minutes later, but better than nothing.

Connect "MicroService Gateway" with "UAA Server" Jhipster 3.5.0

I created a UAA Server:
? (1/16) Which *type* of application would you like to create? [BETA] JHipster UAA server (for microservice OAuth2 authentication)
And I created a Microservicio Gateway:
? (1/16) Which *type* of application would you like to create? Microservice gateway
...
? (6/16) What is the folder path of your UAA application?. ../elseruaa
I created the docker containers, in "docker-compose", and creates well.
I have to add some extra configuration on the gateway to work with the server UAA?
I get the following error trace in the container gateway:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.security.oauth2.provider.token.TokenStore org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration.tokenStore; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tokenStore' defined in class path resource [com/abalia/elser/config/MicroserviceSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.oauth2.provider.token.TokenStore]: Factory method 'tokenStore' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jwtAccessTokenConverter' defined in class path resource [com/abalia/elser/config/MicroserviceSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter]: Factory method 'jwtAccessTokenConverter' threw exception; nested exception is java.lang.IllegalStateException: No instances available for elseruaa...
Thank you very much for your help.
I created a youtube screencast to show how to create jhipster (3.5.1) microservices with UAA. I believe the problems you are facing have to do with the order of startup of services or that old services were not regenerated with 3.5.0+ code. As you can see in the screencast and from the sourcecode on github, it works as is.
screencast
I had the same issue. After spending hours, finally fixed the error by adding following in MicroserviceSecurityConfiguration.java:
Inject org.springframework.cloud.client.discovery.DiscoveryClient
#Inject
private DiscoveryClient discoveryClient;
In any method of MicroserviceSecurityConfiguration.java (I choose getKeyFromAuthorizationServer method), add following:
discoveryClient.getServices();
Caused by: java.lang.IllegalStateException: No instances available for elseruaa reported by RibbonLoadBalancerClient.
I'm not up to date with our uaa support but it seems that your gateway was unable to find a service named elseruaa in the list of Eureka clients that have registered to your JHipster registry (Eureka server). So either you forgot to start elseruaa or it registered with another name.
Change your MobileSecurityConfiguration
#Inject
private DiscoveryClient discoveryClient;
private String getKeyFromAuthorizationServer() {
List<String> services = discoveryClient.getServices();
HttpEntity<Void> request = new HttpEntity<Void>(new HttpHeaders());
String value = (String) this.keyUriRestTemplate
.exchange("http://uaa/oauth/token_key", HttpMethod.GET, request, Map.class).getBody()
.get("value");
return value;
}
so basically that one line :
List<String> services = discoveryClient.getServices();
fix that problem.

Unable to Install NServiceBus Host Windows Service

I'm attempting to follow the instructions to install the windows service host using NServiceBus.Host.exe for the VideoStore sample app. I'm following the instructions from the web site.
My application runs fine when doing an F5 session in Visual Studio. It's hosting using the console app mode for the host. When I attempt to use the command line to perform the installation, I get multiple errors.
The command line I'm running is:
NServiceBus.Host.exe /install /serviceName:"VideoStore.Sales"
/displayName:"VideoStore.Sales" /description:"Endpoint for
VideoStore.Sales"
/endpointConfigurationType:"VideoStore.Sales.EndpointConfig,
VideoStore.Sales" /username:".\MySvc" /password:"MyPassword"
NServiceBus.Production
Running this resulted in the following exception:
Initializing the installer in the Install AppDomain
Unhandled Exception: System.InvalidOperationException: Sequence
contains more than one matching element at
System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source,
Func2 predicate) at
System.Linq.Enumerable.WhereSelectArrayIterator2.MoveNext() at
System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext() at
System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at
NServiceBus.Hosting.Profiles.ProfileManager..ctor(List1
assembliesToScan, IConfigureThisEndpoint specifier, String[] args,
List`1 defaultProfiles)
It turns out, this error is caused because my application is referencing both the NServiceBus.Host assembly as well as the NServiceBus.Hosting.Azure assembly. This is because my application is being deployed both in a Windows environment as well as to an Azure worker role. I can switch between the azure emulator and the console-mode for worker roles without issue simply by changing which projects i'm starting when debugging. (Azure cloud service project vs each of the worker projects.)
I was able to resolve this by deleting the NServiceBus.Hosting.Azure.dll assembly to prevent the assembly scanning from finding it. IMHO, this is a bug. Either allow me to specify the host type explicitly or handle a scenario where multiple types are found.
This stopped the previous exception, and instead introduced a new one:
Unhandled Exception:
System.Configuration.ConfigurationErrorsException: Command line
argument 'endpointConfigurationType' has specified to use the type
'VideoStore.Sales.EndpointConfig, VideoStore.Sales' but that type
could not be loaded. at
NServiceBus.Hosting.Windows.EndpointTypeDeterminer.TryGetEndpointConfigurationTypeFromArguments(HostArguments
arguments, Type& type) in y:\BuildAgent\work
\31f8c64a6e8a2d7c\src\NServiceBus.Hosting.Windows\EndpointTypeDeterminer.cs:line
101 at NServiceBus.Hosting.Windows.Program.Main(String[] args) in
y:\BuildAgent\work\31f8c64a6e8a2d7c\src\NServiceBus.Hosting.Windows\Program.cs:line
38
Both that type and that assembly exist. I've even verified that .NET is loading the type via enabling fusion loader logging:
The operation was successful. Bind result: hr = 0x0. The operation
completed successfully.
Assembly manager loaded from:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll Running under
executable
C:\Projects\Testing\NServiceBus.Azure.Samples-master\VideoStore.AzureServiceBus.Cloud\VideoStore.Sales\bin\Debug\NServiceBus.Host.exe
--- A detailed error log follows.
=== Pre-bind state information === LOG: DisplayName = VideoStore.Sales (Partial) WRN: Partial binding information was supplied for an
assembly: WRN: Assembly Name: VideoStore.Sales | Domain ID: 1 WRN: A
partial bind occurs when only part of the assembly display name is
provided. WRN: This might result in the binder loading an incorrect
assembly. WRN: It is recommended to provide a fully specified textual
identity for the assembly, WRN: that consists of the simple name,
version, culture, and public key token. WRN: See whitepaper
http://go.microsoft.com/fwlink/?LinkId=109270 for more information and
common solutions to this issue. LOG: Appbase =
file:///C:/Projects/Testing/NServiceBus.Azure.Samples-master/VideoStore.AzureServiceBus.Cloud/VideoStore.Sales/bin/Debug/
LOG: Initial PrivatePath = NULL LOG: Dynamic Base = NULL LOG: Cache
Base = NULL LOG: AppName = NServiceBus.Host.exe Calling assembly :
NServiceBus.Host, Version=4.6.0.0, Culture=neutral,
PublicKeyToken=9fc386479f8a226c.
What am I doing wrong here?
EDIT
I believe I see the issue. Basically, trying to avoid the first error where NServiceBus is resolving multiple Profiles due to the fact it's finding them in both NServiceBus.Core and NServicebus.Hosting.Azure is causing the second error.
This is because in order to load my EndpointConfig type, .NET also needs to load the NServicebus.Hosting.Azure assembly, as it implements AsA_Worker, which lives in NServiceBus.Hosting.Azure.
So be deleting that assembly, I'm preventing it from loading the EndpointConfig.
I'm still unclear as to how to resolve this. I need to get NServiceBus to stop scanning both hosting assemblies. This suggests that christof13's answer is correct, but I'm unable to get NServiceBus to ignore its own assemblies.
The root cause of this issue is that when NServiceBus enumerates profiles available, it scans all available assemblies and then does a LINQ statement to filter them down by type name.
The problem is that there are two NServiceBus.Production profiles, one defined in the NServiceBus.Host.dll, and one in the NServiceBus.Hosting.Azure assembly. Their type names are identical, and so the LINQ SingleOrDefault fails.
The suggestion to filter the assemblies searched wouldn't work because NServiceBus always loads its own assemblies. The filter only applies to my project's assemblies.
I was able to resolve this by creating a custom profile that doesn't have the same name as any other profile defined in any assemblies in my project. Something like:
public class DualCloudLocalProfile : IProfile {}
public class DualCloudLocalProfileHandler : IHandleProfile<DualCloudLocalProfile>
{
public void ProfileActivated()
{
if (LogManager.LoggerFactory is NullLoggerFactory || LogManager.LoggerFactory == null)
{
Configure.Instance.TraceLogger().ConsoleLogger();
}
}
}
public class CloudProfileLoggingHandler : IConfigureLoggingForProfile<DualCloudLocalProfile>
{
public void Configure(IConfigureThisEndpoint specifier)
{
//nothing for now
}
}
Once this was added into my project, I modified the install command to specify the new profile:
NServiceBus.Host.exe /install /serviceName:"VideoStore.Sales" /displayName:"VideoStore.Sales" /description:"Endpoint for VideoStore.Sales" /endpointConfigurationType:"VideoStore.Sales.EndpointConfig, VideoStore.Sales" /username:".\MySvc" /password:"MyPassword" VideoStore.Sales.DualCloudLocalProfile
This resolved the problem. I can now run the project as a cloud service and a NServiceBus.Host.exe hosted service, as well as deploy via the /install command for the host.
You can try to filter the assemblies with one the following methods
Configure.With(string probeDirectory)
Configure.With(params Assembly[] assemblies)
Configure.With(IEnumerable<Type> typesToScan)
By default I think that nservicebus scans all the assemblies in the folder, so if you filter with only the needed assemblies it will prevent from receiving this kind of error
http://docs.particular.net/nservicebus/the-nservicebus-host

Unity MVC GetService In Background Thread throws NullReferenceException

As far as I know the DependencyResolver is Thread-Safe, however, running the following code throws a null reference exception in a background thread.
public interface ITest {
}
public class Test : ITest {
}
//this works fine
var service = DependencyResolver.Current.GetService<ITest>();
var t1 = Task.Run(() => {
//This throws a Null Reference exception.
// note that DependencyResolver.Current is NOT null.
// The exception occurs in GetService
var s1 = DependencyResolver.Current.GetService<ITest>();
});
Task.WaitAll(t1);
Here's the stack trace:
at Unity.Mvc4.UnityDependencyResolver.get_ChildContainer()
at Unity.Mvc4.UnityDependencyResolver.IsRegistered(Type typeToCheck)
at Unity.Mvc4.UnityDependencyResolver.GetService(Type serviceType)
at System.Web.Mvc.DependencyResolverExtensions.GetService[TService](IDependencyResolver resolver)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
I'm aware that the "Service Locator" pattern is an anti-pattern. At this point I'm just trying to understand why this doesn't work.
Any insights would be appreciated.
Thanks!
From the stack trace it is clear that you are using the the Unity.Mvc4 NuGet package, which is some unofficial package and is not published by Microsoft. This package contains a bug. Its UnityDependencyResolver.ChildContainer property calls HttpContext.Current.Items without checking whether HttpContext.Current is null and it causes a NullReferenceException when instances are resolved outside the context of a web request.
So instead of using that unofficial NuGet package, I think you're better off using the official NuGet package.

TinyIoC.TinyIoCResolutionException: Unable to resolve type: on ipad deployment

I'm getting TinyIOC Unable to resolve type exception. I have developed my app using Xamarin studio for ipad. In simulator it is working fine. But on deploying ipad i'm getting below error.
TinyIoC.TinyIoCResolutionException: Unable to resolve type: IOSLoginViewModel ---> System.Exception: Unable to resolve type: IOSLoginViewModel ---> System.Exception: Unable to resolve type:
private IEnumerable<ConstructorInfo> GetTypeConstructors(Type type)
{
//#if NETFX_CORE
// return type.GetTypeInfo().DeclaredConstructors.OrderByDescending(ctor => ctor.GetParameters().Count());
//#else
return type.GetConstructors().OrderByDescending(ctor => ctor.GetParameters().Count());
//#endif
}
Above method is returning value on simulator but for ipad it is giving null.
Lines of code I have used is
var tContainer = TinyIoC.TinyIoCContainer.Current;
tContainer.Register<IOnlineAuthenticationService, Framework.OnlineProvider.AuthenticationService>().AsMultiInstance();
DataContext = TinyIoC.TinyIoCContainer.Current.Resolve<IOSLoginViewModel>();
IOS Build options I have tried all,
Linking - SDK, ALL, No but still same error.
In Xamarin Studio, open "Run" -> "Exceptions" and add "System.Exception".
Run your
Run you app
When the error occurs, take a look at the exception object's InnerException property which will give you clues why the type could not be resolved.

Resources