Taritsyn / JavaScriptEngineSwitcher

JavaScript Engine Switcher determines unified interface for access to the basic features of popular JavaScript engines. This library allows you to quickly and easily switch to using of another JavaScript engine.
Apache License 2.0
439 stars 49 forks source link

Error occured "The type initializer for '<Module>' threw an exception." when publishing #85

Closed rollrat closed 4 years ago

rollrat commented 4 years ago
Failed to create instance of the V8JsEngine. See the original error message: “The type initializer for '<Module>' threw an exception.”.
   at JavaScriptEngineSwitcher.V8.V8JsEngine..ctor(V8Settings settings)
   at JavaScriptEngineSwitcher.V8.V8JsEngineFactory.CreateEngine()
   at JavaScriptEngineSwitcher.Core.JsEngineSwitcher.CreateEngine(String name)
   at koromo_copy_backend.Script.KoromoScriptInstance.CreateNewInstance()
   at koromo_copy_backend.Script.ScriptManager.Initialization()
   at koromo_copy_backend.Command.ProcessStartsWithClient()
   at koromo_copy_backend.Command.Start(String[] arguments)
   at koromo_copy_backend.Program.Main(String[] args)
        static bool init = false;
        static void configure()
        {
            if (init) return;
            init = true;
            var engineSwitcher = JsEngineSwitcher.Current;
            engineSwitcher.EngineFactories.Add(new V8JsEngineFactory());
            engineSwitcher.DefaultEngineName = V8JsEngine.EngineName;
        }

        public static KoromoScriptInstance CreateNewInstance()
        {
            configure();
            var engine = JsEngineSwitcher.Current.CreateEngine(V8JsEngine.EngineName);

            engine.EmbedHostType("_native", typeof(_Native));

            return new KoromoScriptInstance(engine);
        }

This error occurs when only the project is built with the following command.

my.csproj:
  <ItemGroup Condition="'$(RuntimeIdentifier)' == 'win10-x86'">
    <PackageReference Include="JavaScriptEngineSwitcher.Core" Version="3.3.0" />
    <PackageReference Include="JavaScriptEngineSwitcher.V8" Version="3.3.1" />
    <PackageReference Include="JavaScriptEngineSwitcher.V8.Native.win-x86" Version="3.3.0" />
  </ItemGroup>

command:
dotnet publish -r win10-x86 -c Release /p:PublishSingleFile=true /p:PublishTrimmed=true

It works normally in the case of ChakraCore, but not in the case of V8. It also works fine in Debug and Release mode, not using publish.

Taritsyn commented 4 years ago

Hello!

Is the Microsoft Visual C++ Redistributable for Visual Studio 2019 installed on computer?

rollrat commented 4 years ago

Hi! I'm using Visual Studio Enterprise 2019 16.4.3.

After checking a few more, it was found that the /p:PublishTrimmed=true option was the cause of the error. According to Microsoft, using this feature may cause the program to stop working when using reflection features or dynamic loading. So, after removing this option, I was able to fix this problem. Thank you for quick response :)