The type initializer for 'NHibernate.Cfg.Configuration' threw an exception - nhibernate

After upgrading from nhibernate 1.0.4.0 to nhibernate 3.3 im encountering the following error when I try to run "Configuration cfg = new Configuration();"
System.TypeInitializationException was caught
Message="The type initializer for 'NHibernate.Cfg.Configuration' threw an exception."
Source="NHibernate"
TypeName="NHibernate.Cfg.Configuration"
StackTrace:
at NHibernate.Cfg.Configuration..ctor()
at KEH.Web.Data.NHibernateUtil..cctor() in F:\Projects\KEH nHibernate\KEHWeb\Data\Data\NHibernateUtil.cs:line 24
InnerException: System.NotSupportedException
Message="The invoked member is not supported in a dynamic assembly."
Source="mscorlib"
StackTrace:
at System.Reflection.Emit.AssemblyBuilder.get_Location()
at log4net.Util.SystemInfo.AssemblyLocationInfo(Assembly myAssembly)
at log4net.Core.DefaultRepositorySelector.GetInfoForAssembly(Assembly assembly, String& repositoryName, Type& repositoryType)
at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly repositoryAssembly, Type repositoryType, String repositoryName, Boolean readAssemblyAttributes)
at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly repositoryAssembly, Type repositoryType)
at log4net.Core.DefaultRepositorySelector.GetRepository(Assembly repositoryAssembly)
at log4net.Core.LoggerManager.GetLogger(Assembly repositoryAssembly, String name)
at log4net.LogManager.GetLogger(Assembly repositoryAssembly, String name)
at log4net.LogManager.GetLogger(Type type)
at lambda_method(ExecutionScope , Type )
at NHibernate.Log4NetLoggerFactory.LoggerFor(Type type)
at NHibernate.LoggerProvider.LoggerFor(Type type)
at NHibernate.Cfg.Configuration..cctor()
InnerException:
Any help would be greatly appreciated.
The NHibernateUtil class code is as follows :
public class NHibernateUtil
{
private static readonly Configuration cfg;
private static readonly ISessionFactory sessionFactory;
private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static NHibernateUtil()
{
try
{
logger.Debug("Before Initializing NHibernate");
cfg = new Configuration();
cfg.AddAssembly("KEH.Web.Data");
sessionFactory = cfg.BuildSessionFactory();
logger.Debug("Initialized NHibernate");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public static ISession OpenSession()
{
logger.Debug("Before Getting Connection");
return sessionFactory.OpenSession();
}
}

I had the same problem.
The actual reason was i used a library that used old version of log4net.
NHibernate tries to use it if find.
So i had to force it to use (or actually not use) other logger by adding such line:
LoggerProvider.SetLoggersFactory(new NoLoggingLoggerFactory());

Not sure why it's not working, but I'd just replace
cfg.AddAssembly("KEH.Web.Data");
with
cfg.AddAssembly(typeof(Entity).Assembly);
where Entity is some class that exists in the assembly of your mapping files.

For the benefit of others who might find this question via Google:
For us, this error was a red-herring. Our app ran fine until we deployed a new component AND it would fail (in an unknown way) AND IIS would recycle the app pool. The problem was an HTML to JPG component we were using was erroring somehow and causing all of our w3wp.exe worker processes to consume maximum CPU. When the app pool was recycled via IIS, the entire site would go down and NHibernate would throw this error continuously until an iisreset. Before the recycle, the site would still be very responsive even with the CPU load.
While we still don't know how the component was failing or why it was cascading to problems with NHibernate initializing, the point is it was a red-herring. Be sure to watch for this error "suddenly" occurring shortly after a new deployment, and keep logs of your CPU utilization so it can help spot when trouble is brewing. Finally, if the downtime is happening near the same time every day, it's probably an automatic IIS app pool recycle, and that should be another clue that something is bugging out your application and surfacing during the recycle.
Ultimately, we disabled the HTML to JPG component until a workaround can be found and our up-time sprung back to 100%.
Hope this helps someone.

Related

Can't get Azure Function .Net 5.0 Dependency Injection to inject service in another Project with dependencies

I am trying to inject a Service into my Azure Function that lives in another Project.
Here is my code.
public static async Task Main()
{
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(s =>
{
s.AddTransient<ILocationService, LocationService>();
})
.Build();
Console.WriteLine("Host running!");
await host.RunAsync();
}
The LocationService is dependent on the DBContext.
private readonly MyAppDBContext _context;
public LocationService(MyAppDBContext context)
{
_context = context;
}
Here is my Function.
private readonly ILocationService _locationService;
private readonly TelemetryClient _telemetryClient;
public Function1(ILocationService locationService, TelemetryConfiguration telemetryConfiguration)
{
_locationService = locationService;
_telemetryClient = new TelemetryClient(telemetryConfiguration);
}
Here is the error.
Result: Failure Exception: System.InvalidOperationException: Unable to resolve service for type 'MyApp.Data.MyAppDBContext' while attempting to activate 'MyApp.Services.LocationService'. at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain) at
I've tried both version 6.0 and 5.0.2 of Microsoft.Extensions.DependencyInjection.
This guide seems to suggest I'm doing it right.
https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide#dependency-injection
Any help is much appreciated! Thanks!
Turns out that this was an issue with Visual Studio 2019. I couldn't get web publishing to work, so I used FTP. To do that, I used the publish to folder method. I then zipped the files and used Power Shell to upload the zip file. Turns out that the publish to folder method was not working properly. It was never updating the files. All the changes I made never made it to the server. So frustrating! I wasted hours and hours on this. Here is what is now working. I also fixed the web publishing method by downloading a new publish profile.
s.AddDbContext<MyDBContext>();
s.AddLogging();
s.AddScoped<IMyService, MyService>();

Blazor HttpClient injection into a ViewModel constructor

I am following the referenced blog/article below, and I am unable to inject an HttpClient to my ViewModel. It works fine the default way (#inject in the razor file). But i am trying to inject into the ViewModel instead.
If i add to the services like the following, then the default injection doesnt work for other razor views which has the #inject HttpClient.
// manually add HttpClient to services.
services.AddTransient<IFetchViewModel, FetchViewModel>();
Question:
How can i inject the default injected HttpClient to my various
ViewModels?
Note that I am getting an exception:
WASM: Unhandled exception rendering component:
WASM: System.Reflection.TargetParameterCountException: Number of parameters specified does not match the expected number.
Reference:
https://itnext.io/a-simple-mvvm-implementation-in-client-side-blazor-8c875c365435
Update
After making suggested changes and then digging deeper during
debugging, i can see that there is something wrong with the json
deserialization. Could this be an issue?
https://github.com/aspnet/Blazor/issues/225
Note that deeper down the exception stack trace, i see the following:
WASM: at SimpleJson.SimpleJson.DeserializeObject (System.String
json, System.Type type, SimpleJson.IJsonSerializerStrategy
jsonSerializerStrategy) <0x2ebc4f0 + 0x00068> in
<8f8c03446dbf45f5bbcb1e109a064f6e>:0 WASM: at
SimpleJson.SimpleJson.DeserializeObject[T] (System.String json)
<0x2ef2490 + 0x0000a> in <8f8c03446dbf45f5bbcb1e109a064f6e>:0 WASM:
at Microsoft.JSInterop.Json.Deserialize[T] (System.String json)
<0x2ef2458 + 0x00004> in <8f8c03446dbf45f5bbcb1e109a064f6e>:0 WASM:
at
Microsoft.AspNetCore.Components.HttpClientJsonExtensions.GetJsonAsync[T]
(System.Net.Http.HttpClient httpClient, System.String requestUri)
<0x33182e0 + 0x000fa> in <13ab8f8dacb6489b93c9655168c56037>:0 WASM:
at WebUI.Features.Fetch.FetchViewModel.LoadAsync () <0x3300de0 +
0x00102> in :0
Updated 2
So i can confirm now that i was barking up the wrong tree.
Essentially, i had a deserialization issue. Once i resolved that issue, everything is working fine. Not sure if i had a DI issue from the beginning or not. Nonetheless, my issue resolved now. Thanks for all the enlightening perspectives.
This is not really an answer to your question; without complete display of your code, no answer is really possible. But let me relate to the following code snippet; perhaps the problem lies there:
// manually add HttpClient to services.
services.AddTransient<IFetchViewModel, FetchViewModel>();
HttpClient service is provided as a Singleton (CSB) by the Blazor framework. Thus you cannot inject HttpClient into a service which you add to your app as Transient. Your service should also be added as Singleton...
Hope this helps...
[Edit]
How can i inject the default injected HttpClient
to my various ViewModels?
If your ViewModels are Components, you may use the #inject directive like this:
#inject HttpClient httpClient
If your ViewModels are ordinary classes (.cs), you can
either pass a reference to an HttpClient object from your calling component methods or inject the HttpClient service to your ViewModels' constructors. Don't forget to add your Services or ViewModels in the Startup class:
services.AddSingleton<IFetchViewModel, FetchViewModel>();
Once again, use AddSingleton
No, your problem has got nothing to do with issue 225.
This issue is very old, and all the bugs referred to in this issue were rectified long before I've heard of Blazor...
Note: The exception stack trace clearly points out in the direction of HttpClient being the culprit. Do what I've suggested above, and tell us if the issue is still persisting.
Why don't you display your code, as others ask you to do. Please look for instruction on how to ask question in stack overflow.
The pattern is easy.
I got it working like this, starting from the standard starter template.
In FetchData.razor:
#page "/fetchdata"
#using ClientBlazor1.ViewModels
#inject FetchDataViewModel vm
... the html
protected override async Task OnInitAsync()
{
forecasts = await vm.GetForecasts();
}
And the ViewModel is below. You seem to be missing the constructor (-injection) part here.
Using an interface is optional, I didn't.
public class FetchDataViewModel
{
private HttpClient _httpClient;
public FetchDataViewModel(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<WeatherForecast[]> GetForecasts()
{
return await _httpClient.GetJsonAsync<WeatherForecast[]>("sample-data/weather.json");
}
}
and to finish it up, the registration part in Startup.cs :
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<FetchDataViewModel>();
}
In general this should not be a Singleton.

ReflectionTypeLoadException in ASP.NET Core MVC application

I'm running into a problem running an ASP.NET Core 1.0 application targeting .NET Framework 4.6. The problem didn't occur until we tried to run the application on a server running Windows Server 2016. The app is hosted in IIS and I have the .NET Core 1.0 Windows Hosting Bundle installed on the server.
Upon loading the site a 500 error is returned and this is written to the Logs:
An unhandled exception has occurred: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. (fc7986d0)
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
Researching this it appears to relate to a missing dll or mismatched version, and that I should look at the LoaderExceptions property to get more info, but I'm not sure how to do that in this instance. The log entry is created just from setting up the loggerFactory in the Configure() method of Startup.cs.
I tried adding an IExceptionFilter ActionFilter implementation and reading the LoaderExceptions property if the exception is of type ReflectionTypeLoadException, but it doesn't get hit when ran on the server.
Is there a way to drill down into the Exception to read the LoaderExceptions property (in a production environment, there is no error when running in Visual Studio so debugging didn't help), or else another way to troubleshoot the original error to determine what is wrong with the server setup?
Instead of using IExceptionFilter, I wrote my own Middleware for catching this sort of exception and was able to log each exception from the LoaderExceptions property and determine what my problem is. Here is what I added to log the LoaderExceptions:
public class ExceptionCatchMiddleware
{
private readonly RequestDelegate _delegate;
private readonly ILogger _logger;
public ExceptionCatchMiddleware(RequestDelegate requestDelegate, ILogger<ExceptionCatchMiddleware> logger)
{
_delegate = requestDelegate;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await _delegate(context);
}
catch (ReflectionTypeLoadException e)
{
foreach (Exception ex in e.LoaderExceptions)
{
_logger.LogCritical(ex.Message + Environment.NewLine + ex.StackTrace);
}
}
}
}
And then I just needed to add the Middleware to the Configure() method in Startup.cs:
app.UseMiddleware<ExceptionCatchMiddleware>();
In my case it was a missing dll that wasn't included in the project but since it was in my dev machine's GAC it ran there just fine.

spring-boot property placeholder

I'm not able to figure out why I am not able to inject values into my application.properties file in spring-boot. external property into the logging.file variable. I have an application.properties file which looks like this
logging.file=${mylogfile}
server.port=${myport}
with corresponding Spring-boot Application class
#PropertySources({
#PropertySource("file:///c:/myfolder/externalprops.properties"),
})
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
and external property file
mylogfile=myoutput.log
myport=8060
When I run my spring-boot 1.0.2.REL application I get the following exception every time I try to inject mylogfile into the logging.file property in application.properties
Exception in thread "main" java.lang.IllegalArgumentException: Could not resolve placeholder 'mylogfile' in string value "${mylogfile}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
Note that I am not having any problems injecting and starting up the application if I inject the server port number on its own.
I am going around in circles on this issue and cannot figure out what I am doing wrong.
I don't think you can use #PropertySource to inject values into "application.properties" - the latter has to be parsed and ready to use before any #Configuration is read, or even known about. Your external properties could go in "${user.dir}/application.properties" and I think that would achieve what you are trying to do.

Move to Web API RC, Get: Method not found: 'System.Web.Http.Services.DependencyResolver System.Web.Http.HttpConfiguration.get_ServiceResolver()'

I moved a site from WebAPI Beta to WebAPI RC, and am now getting an error upon loading the site: Method not found: 'System.Web.Http.Services.DependencyResolver System.Web.Http.HttpConfiguration.get_ServiceResolver()'.
The error occurs the first time that I am trying to register my AutoFacWebApiDependencyResolver (per instructions here):
var resolver = new AutofacWebApiDependencyResolver(IoCManager.Container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
The stacktrace shows the following:
[MissingMethodException: Method not found: 'System.Web.Http.Services.DependencyResolver System.Web.Http.HttpConfiguration.get_ServiceResolver()'.]
System.Web.Http.GlobalConfiguration.<.cctor>b__0() +0
System.Lazy`1.CreateValue() +12775823
System.Lazy`1.LazyInitValue() +355
StatusBoard.Web.MvcApplication.RegisterDependencyInjection() in C:\path-tp-app\Global.asax.cs:125
StatusBoard.Web.MvcApplication.Application_Start() in C:\path-to-app\Global.asax.cs:75
Based on this, it appears that the error is occurring during initialization of the static GlobalConfiguration class. When I drill down into the source for that class, I see the following:
private static Lazy<HttpConfiguration> _configuration = new Lazy<HttpConfiguration>((Func<HttpConfiguration>) (() =>
{
local_0 = new HttpConfiguration((HttpRouteCollection) new HostedHttpRouteCollection(RouteTable.Routes));
local_0.get_ServiceResolver().SetService(typeof (IBuildManager), (object) new WebHostBuildManager());
return local_0;
}));
private static Lazy<HttpControllerDispatcher> _dispatcher = new Lazy<HttpControllerDispatcher>((Func<HttpControllerDispatcher>) (() => new HttpControllerDispatcher(GlobalConfiguration._configuration.Value)));
public static HttpConfiguration Configuration
{
get
{
return GlobalConfiguration._configuration.Value;
}
}
The fourth line here seems to be the issue - it is trying to call a get_ServiceResolver() method that no longer exists in the HttpConfiguration class (should be DependncyResolver instead, probably).
Is this just a bug with the RC for WebAPI? Is there some way that I can get around this? Or am I stuck in some DLL/Nuget hell (and if so, how can I extricate myself)?
be sure to include the correct nuget package (RC!) and install the new mvc4rc on the machine where you build your package.
Dependency Resolution has been completely re-written in RC. Best is to uninstall beta DLLs and then your problems most likely go away.
Just uninstall the one flagged as "(bundle)" in windows' "Uninstall a program".