NServiceBus.CommonObjectBuilder in assembly NServiceBus.Core, Version=7.0.0.0, Culture=neutral, PublicKeyToken=9fc386479f8a226c not marked as serializable

Upgradeded from 7.7.3 to 7.7.4, got this Fatal error at start of endpoint when NHibernate was setting up.

NServiceBus.CommonObjectBuilder in assembly NServiceBus.Core, Version=7.0.0.0, Culture=neutral, PublicKeyToken=9fc386479f8a226c not marked as serializable

Using Nservicebus.Host 8.5 and NHibernate

Fixed by downgrading to 7.7.3

Can you share environment details like .NET and OS versions?

Is it also possible that you provide the full stack trace of the exception?

Looking at the diff Comparing 7.7.3...7.7.4 · Particular/NServiceBus · GitHub it seems that the class has the sealed keyword added.

.NET 4.8, OS Windows 10 (same error on our Windows server, so OS probably not involved) a bit swedish in the stacktrace.

2022-08-23 13:24:29.119 FATAL Start failure
System.TypeInitializationException: Typinitieraren för NHibernate.Cfg.Environment utlöste ett undantag. ---> System.Runtime.Serialization.SerializationException: Typen NServiceBus.CommonObjectBuilder i sammansättningen NServiceBus.Core, Version=7.0.0.0, Culture=neutral, PublicKeyToken=9fc386479f8a226c är inte deklarerad som serialiserbar.
   vid System.AppDomain.get_Evidence()
   vid System.AppDomain.get_Evidence()
   vid System.Configuration.ClientConfigPaths.GetEvidenceInfo(AppDomain appDomain, String exePath, String& typeName)
   vid System.Configuration.ClientConfigPaths.GetTypeAndHashSuffix(AppDomain appDomain, String exePath)
   vid System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)
   vid System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)
   vid System.Configuration.ClientConfigurationHost.RequireCompleteInit(IInternalConfigRecord record)
   vid System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
   vid System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
   vid System.Configuration.ConfigurationManager.GetSection(String sectionName)
   vid NHibernate.Cfg.StaticConfigurationManagerProvider.GetConfiguration()
   vid NHibernate.Cfg.Environment.GetHibernateConfiguration()
   vid NHibernate.Cfg.Environment..cctor()
   --- Slut på stackspårning för interna undantag ---
   vid NHibernate.Cfg.Environment.get_Properties()
   vid NHibernate.Cfg.Configuration.Reset()
   vid NServiceBus.Persistence.NHibernate.NHibernateConfigurationBuilder.CreateNHibernateConfiguration()
   vid NServiceBus.Persistence.NHibernate.NHibernateConfigurationBuilder.InitFromConfiguration(ReadOnlySettings settings)
   vid NServiceBus.Persistence.NHibernate.NHibernateConfigurationBuilder..ctor(ReadOnlySettings settings, Object diagnosticsObject, String connectionStringKeySuffix, String specificConfigSetting)
   vid CallSite.Target(Closure , CallSite , Type , ReadOnlySettings , Object , String , String )
   vid System.Dynamic.UpdateDelegates.UpdateAndExecute5[T0,T1,T2,T3,T4,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
   vid NServiceBus.Features.NHibernateSubscriptionStorage.Setup(FeatureConfigurationContext context)
   vid NServiceBus.Features.FeatureActivator.FeatureInfo.InitializeFrom(FeatureConfigurationContext featureConfigurationContext)
   vid NServiceBus.Features.FeatureActivator.ActivateFeature(FeatureInfo featureInfo, List`1 featuresToActivate, FeatureConfigurationContext featureConfigurationContext)
   vid NServiceBus.Features.FeatureActivator.SetupFeatures(FeatureConfigurationContext featureConfigurationContext)
   vid NServiceBus.FeatureComponent.Initalize(FeatureConfigurationContext featureConfigurationContext)
   vid NServiceBus.EndpointCreator.Initialize()
   vid NServiceBus.EndpointCreator.Create(SettingsHolder settings, Configuration hostingConfiguration)
   vid NServiceBus.HostCreator.<CreateWithInternallyManagedContainer>d__1.MoveNext()

@Jonas I tried reproducing this using our simple sample:

That sample runs without any issues. Could you share more details like your endpoint configuration and nhibernate configuration and dependency injection initialization code as it currently seems this might be related to some type scanning issue.

public class WorkerEndpointConfig : IConfigureThisEndpoint
{
    public void Customize(EndpointConfiguration configuration)
    {
        var container = ServiceFactory.BuildContainer<FacadeInstaller>();
        log4net.Config.XmlConfigurator.Configure(
            new System.IO.FileInfo(
                AppDomain.CurrentDomain.SetupInformation.ConfigurationFile));
        
        configuration.UsePersistence<NHibernatePersistence>();

        var transport = configuration.UseTransport<MsmqTransport>();

        var routing = transport.Routing();

        routing.RouteToEndpoint(assembly: typeof(UtforPersonkontrollResponse).Assembly, "XXXXX.VO.AAG.API.Process.Messages", ConfigurationManager.AppSettings["MessageEndpointMapping.XXXXX.VO.AAG.API.Process"]);
        routing.RouteToEndpoint(assembly: typeof(MeddelaNyPersonKund).Assembly, "XXXXX.VO.AAG.API.Process.Commands", ConfigurationManager.AppSettings["MessageEndpointMapping.XXXXX.VO.AAG.API.Process"]);
        routing.RouteToEndpoint(assembly: typeof(SkapaPersonkundWorker).Assembly, "XXXXX.VO.AAG.API.Worker.Commands", ConfigurationManager.AppSettings["MessageEndpointMapping.XXXXX.VO.AAG.API.Worker"]);
        routing.RouteToEndpoint(assembly: typeof(SkickaEpost).Assembly, ConfigurationManager.AppSettings["MessageEndpointMapping.XXXXX.VO.GAA.API"]);

        configuration.UseContainer<WindsorBuilder>(c => c.ExistingContainer(container));
        configuration.LimitMessageProcessingConcurrencyTo(1);

        configuration.Conventions()
            .DefiningMessagesAs(
                type =>
                    type.Namespace != null && 
                    type.Namespace.EndsWith(".Messages") && 
                    type.Namespace.StartsWith("XXXXX.") ||
                   (type.Namespace != null && 
                    type.Namespace.EndsWith(".Internal") && 
                    type.Namespace.StartsWith("XXXXX.")))
            .DefiningCommandsAs(type => type.Namespace != null && 
                                type.Namespace.EndsWith(".Commands") && 
                                type.Namespace.StartsWith("XXXXX."));

        var recoverability = configuration.Recoverability();
        recoverability.Immediate(immediate => { immediate.NumberOfRetries(3); });
        recoverability.Delayed(delayed => { delayed.NumberOfRetries(3); });

        configuration.SendFailedMessagesTo(ConfigurationManager.AppSettings["ErrorQueue"]);
        configuration.AuditProcessedMessagesTo(ConfigurationManager.AppSettings["AuditQueue"]);
    }
}

And FacadeInstaller that registers components in the container:

public class FacadeInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Types.FromAssemblyContaining<AAGFacade>().Where(
                type => type.IsPublic && type.Name.EndsWith("AuthorizationConfig"))
                .WithService.AllInterfaces().Configure(c => c.LifestyleTransient()));

    }
}

Don’t know that any of this gives you a clue, only difference between working and not working is 7.7.3 and 7.7.4.

We also experience the same issue when upgrading NServiceBus to either 7.7.4 or the newer 7.8.0.

1 Like

I have the same issue on my testing environment on 7.7.4. Downgrading to 7.7.3 resolved it. On my development machine I did not experience this issue.

The testing environment is running on .NET Framework 4.7.2 and Windows Server 2008 R2. My local development machine is Windows 10. I’m using the following NSB package versions:

<PackageReference Include="NServiceBus" Version="7.4.4" />
<PackageReference Include="NServiceBus.CastleWindsor" Version="7.2.0" />
<PackageReference Include="NServiceBus.Metrics.PerformanceCounters" Version="4.0.0" />
<PackageReference Include="NServiceBus.Newtonsoft.Json" Version="2.3.0" />
<PackageReference Include="NServiceBus.Persistence.Sql" Version="6.5.1" />
<PackageReference Include="NServiceBus.ProtoBufGoogle" Version="2.0.0" />
<PackageReference Include="NServiceBus.RabbitMQ" Version="6.1.1" />
<PackageReference Include="NServiceBus.Transport.Msmq" Version="1.2.1" />

I checked out the simple sample @ramonsmits linked, and I’m also unable to reproduce the error with that, on either my development machine or testing environment.

System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlConnection' threw an exception. ---> System.Runtime.Serialization.SerializationException: Type 'NServiceBus.CommonObjectBuilder' in assembly 'NServiceBus.Core, Version=7.0.0.0, Culture=neutral, PublicKeyToken=9fc386479f8a226c' is not marked as serializable.
   at System.AppDomain.get_Evidence()
   at System.AppDomain.get_Evidence()
   at System.Configuration.ClientConfigPaths.GetEvidenceInfo(AppDomain appDomain, String exePath, String& typeName)
   at System.Configuration.ClientConfigPaths.GetTypeAndHashSuffix(AppDomain appDomain, String exePath)
   at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)
   at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)
   at System.Configuration.ClientConfigurationHost.RequireCompleteInit(IInternalConfigRecord record)
   at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
   at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
   at System.Configuration.ConfigurationManager.GetSection(String sectionName)
   at System.Data.SqlClient.SqlConnection..cctor()
   --- End of inner exception stack trace ---
   at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
   at Custom.MessageBusInitializer.<>c__DisplayClass5_1.<ApplyEndpointConfiguration>b__13()
   at SynchronizedStorage.<OpenSession>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NServiceBus.LoadHandlersConnector.<AdaptOrOpenNewSynchronizedStorageSession>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NServiceBus.LoadHandlersConnector.<Invoke>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at CurrentSessionBehavior.<Invoke>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NServiceBus.ScheduledTaskHandlingBehavior.<Invoke>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NServiceBus.InvokeSagaNotFoundBehavior.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NServiceBus.DeserializeMessageConnector.<Invoke>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at ReceivePerformanceDiagnosticsBehavior.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NServiceBus.ProcessingStatisticsBehavior.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NServiceBus.TransportReceiveToPhysicalMessageConnector.<Invoke>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NServiceBus.RetryAcknowledgementBehavior.<Invoke>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NServiceBus.MainPipelineExecutor.<Invoke>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NServiceBus.TransportReceiver.<InvokePipeline>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at NServiceBus.TransportReceiver.<InvokePipeline>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NServiceBus.Transport.RabbitMQ.MessagePump.<Process>d__34.MoveNext()

The one line of my code in the stack trace is the sqlPersistence.ConnectionBuilder(..) func:

   at Custom.MessageBusInitializer.<>c__DisplayClass5_1.<ApplyEndpointConfiguration>b__13()
var sqlPersistence = endpointConfiguration.UsePersistence<SqlPersistence>();
sqlPersistence.SqlDialect<SqlDialect.MsSqlServer>();
sqlPersistence.ConnectionBuilder(() => new SqlConnection(ConfigurationManager.ConnectionStrings[sqlPersistenceConnectionStringName].ConnectionString));
1 Like

It could be that you are affected by

It lists 2 workarounds.of which the 2nd workaround is also applied by ourselves. More details on that mitigation is available at https://learn.microsoft.com/en-us/dotnet/framework/migration-guide/mitigation-deserialization-of-objects-across-app-domains

Please share if applying either workaround resolves your problem.

Side note, a change in Core exposed this issue but it is as explained above a SqlClient issue. It also seems that is issue only happens when using .NET Framework and not when using .NET (Core) so a 3rd workaround could be upgrading to .NET 6.