aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

MissingMethodException occured when deploying Blazor Server app with 'Trim Unused code'

Open yangzhongke opened this issue 2 years ago • 18 comments

Is there an existing issue for this?

  • [X] I have searched the existing issues

Describe the bug

I created an Blazor Server application using the default template on .NET 6, and deploy it with the option 'Trim Unused code' as self-contained. Then, I ran the application, and launched the page in browser, and the 'System.MissingMethodException: Cannot dynamically create an instance of type 'Microsoft.AspNetCore.Components.Web.HeadOutlet'. Reason: No parameterless constructor defined.' occurred. When I checked HeadOutlet class of the generated Microsoft.AspNetCore.Components.Web.dll, I found that the HeadOutlet class is a empty class. image

If I deployed the application without the option 'Trim Unused code', the generated Microsoft.AspNetCore.Components.Web.dll is normal, and no exceptions occurred.

Source code: https://1drv.ms/u/s!AsFi0-jzsGnQawMBCLgbBt2PYGg?e=BviG3k

Expected Behavior

No response

Steps To Reproduce

  1. Create a Blazor Server application.
  2. Deploy the application with the option 'Trim Unused code' as self-contained.
  3. Run the deployed binaries. image

Exceptions (if any)

fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1] An unhandled exception has occurred while executing the request. System.MissingMethodException: Cannot dynamically create an instance of type 'Microsoft.AspNetCore.Components.Web.HeadOutlet'. Reason: No parameterless constructor defined. at System.RuntimeType.ActivatorCache..ctor(RuntimeType ) at System.RuntimeType.CreateInstanceDefaultCtor(Boolean , Boolean ) at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at System.Activator.CreateInstance(Type type) at Microsoft.AspNetCore.Components.DefaultComponentActivator.CreateInstance(Type ) at Microsoft.AspNetCore.Components.ComponentFactory.InstantiateComponent(IServiceProvider , Type ) at Microsoft.AspNetCore.Components.RenderTree.Renderer.InstantiateComponent(Type ) at Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.CreateInitialRenderAsync(Type componentType, ParameterView initialParameters) at Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.RenderComponentAsync(Type componentType, ParameterView initialParameters) at Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext.<>c__111.<<InvokeAsync>b__11_0>d.MoveNext() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.ViewFeatures.StaticComponentRenderer.PrerenderComponentAsync(ParameterView parameters, HttpContext httpContext, Type componentType) at Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.PrerenderedServerComponentAsync(HttpContext context, ServerComponentInvocationSequence invocationId, Type type, ParameterView parametersCollection) at Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.RenderComponentAsync(ViewContext viewContext, Type componentType, RenderMode renderMode, Object parameters) at Microsoft.AspNetCore.Mvc.TagHelpers.ComponentTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output) at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, Int32 i, Int32 count) at BlazorApp1.Pages.Pages__Layout.<ExecuteAsync>b__14_0() in C:\Users\cowne\source\repos\BlazorApp1\BlazorApp1\Pages\_Layout.cshtml:line 14 at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync() at BlazorApp1.Pages.Pages__Layout.ExecuteAsync() at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context) at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts) at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderLayoutAsync(ViewContext context, ViewBufferTextWriter bodyWriter) at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context) at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable1 statusCode) at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)

.NET Version

6.0.101

Anything else?

Microsoft Visual Studio Professional 2022 (64-bit) Version 17.0.5

.NET SDK: Version: 6.0.101 Commit: ef49f6213a

OS Name: Windows OS Version: 10.0.19044 OS Platform: Windows RID: win10-x64 Base Path: C:\Program Files\dotnet\sdk\6.0.101\

Host (useful for support): Version: 6.0.1 Commit: 3a25a7f1cc

.NET SDKs installed: 5.0.402 [C:\Program Files\dotnet\sdk] 6.0.101 [C:\Program Files\dotnet\sdk]

.NET runtimes installed: Microsoft.AspNetCore.App 5.0.11 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 6.0.1 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.NETCore.App 5.0.11 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 6.0.0-rc.2.21480.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 6.0.1 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.WindowsDesktop.App 5.0.11 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 6.0.0-rc.2.21501.6 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 6.0.1 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]

yangzhongke avatar Feb 07 '22 13:02 yangzhongke

This is similar to https://github.com/dotnet/aspnetcore/issues/37143, but with Server rendering, not WASM. Could you use https://github.com/dotnet/aspnetcore/issues/37143#issuecomment-931726256 as a workaround to unblock yourself?

pranavkm avatar Feb 07 '22 14:02 pranavkm

Thanks for contacting us.

We're moving this issue to the .NET 7 Planning milestone for future evaluation / consideration. We would like to keep this around to collect more feedback, which can help us with prioritizing this work. We will re-evaluate this issue, during our next planning meeting(s). If we later determine, that the issue has no community involvement, or it's very rare and low-impact issue, we will close it - so that the team can focus on more important and high impact issues. To learn more about what to expect next and how this issue will be handled you can read more about our triage process here.

ghost avatar Feb 07 '22 17:02 ghost

@yangzhongke can you try out the latest .NET 6.0 SDK release and see whether you can still hit this issue? Thanks

mkArtakMSFT avatar Apr 13 '22 16:04 mkArtakMSFT

Hi @yangzhongke. We have added the "Needs: Author Feedback" label to this issue, which indicates that we have an open question for you before we can take further action. This issue will be closed automatically in 7 days if we do not hear back from you by then - please feel free to re-open it if you come back to this issue after that time.

ghost avatar Apr 13 '22 16:04 ghost

We've moved this issue to the Backlog milestone. This means that it is not going to be worked on for the coming release. We will reassess the backlog following the current release and consider this item at that time. To learn more about our issue management process and to have better expectation regarding different types of issues you can read our Triage Process.

ghost avatar Apr 13 '22 16:04 ghost

HeadOutlet

Thanks for your reply. However, it still doesn't work. .NET SDK version: 6.0.4 VS version: 17.1.4 image

image

yangzhongke avatar Apr 14 '22 01:04 yangzhongke

This still happens in .NET 7 Preview 7.

chrdlx avatar Aug 25 '22 04:08 chrdlx

System.MissingMethodException: Method not found: 'Void Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor..ctor(Microsoft.AspNetCore.Mvc.Infrastructure.OutputFormatterSelector, Microsoft.AspNetCore.Mvc.Infrastructure.IHttpResponseStreamWriterFactory, Microsoft.Extensions.Logging.ILoggerFactory)'. at JMCKnow.Domain.Results.RequestFailedResultExecutor..ctor(OutputFormatterSelector formatterSelector, IHttpResponseStreamWriterFactory writerFactory, ILoggerFactory loggerFactory) at System.RuntimeMethodHandle.InvokeMethod(Object target, Span1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions) at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType) at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func`2 valueFactory) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider) at JMCKnow.Domain.Helpers.HttpContextExtensions.WriteResultAsync[TResult](HttpContext context, TResult result) in D:\localhost\JMC\jmc-know-api\JMCKnow\JMCKnow.Domain\Helpers\HttpContextExtensions.cs:line 24 at JMCKnow.Api.Middlewares.CustomExceptionMiddleware.HandleNotFoundExceptionAsync(HttpContext context, NotFoundException exception) in D:\localhost\JMC\jmc-know-api\JMCKnow\JMCKnow.Api\Middlewares\CustomExceptionMiddleware.cs:line 124 at JMCKnow.Api.Middlewares.CustomExceptionMiddleware.InvokeAsync(HttpContext httpContext) in D:\localhost\JMC\jmc-know-api\JMCKnow\JMCKnow.Api\Middlewares\CustomExceptionMiddleware.cs:line 60 at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

image

image

jaydeep5890 avatar Sep 14 '22 15:09 jaydeep5890

@yangzhongke can you try out the latest .NET 6.0 SDK release and see whether you can still hit this issue? Thanks

yse,latest .NET 6.0 SDK release can still hit this issue!

hanxiao123 avatar Oct 08 '22 09:10 hanxiao123

It seems like the trimmer had trimmed away the parameterless constructor due to it is obviously not used statically unless it is under reflection context. This issue is prominent in running with deserialization framework, and with the use of record where you cannot force to create a parameterless constructor I think.

wizpresso-steve-cy-fan avatar Nov 22 '22 04:11 wizpresso-steve-cy-fan

Cc @eerhardt

danmoseley avatar Nov 22 '22 04:11 danmoseley

This also happens in .NET 7.0 in my MAUI Blazor project: https://github.com/Jinjinov/Ididit

I can disable trimming for Linux and Android, but there is no way to disable trimming for iOS and macOS

Arg_NoDefCTor, Microsoft.AspNetCore.Components.Web.HeadOutlet
   at System.RuntimeType.CreateInstanceMono(Boolean , Boolean )
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean , Boolean )
   at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)
   at Blazorise.ComponentActivator.CreateInstance(Type componentType)
   at Microsoft.AspNetCore.Components.ComponentFactory.InstantiateComponent(IServiceProvider , Type )
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.InstantiateComponent(Type )
   at Microsoft.AspNetCore.Components.RenderTree.WebRenderer.AddRootComponent(Type , String )
   at Microsoft.AspNetCore.Components.WebView.Services.WebViewRenderer.AddRootComponent(Type componentType, String domElementSelector)
   at Microsoft.AspNetCore.Components.WebView.WebViewManager.AttachToPageAsync(String baseUrl, String startUrl)
   at Microsoft.AspNetCore.Components.WebView.IpcReceiver.OnMessageReceivedAsync(PageContext pageContext, String message)
   at Microsoft.AspNetCore.Components.WebView.WebViewManager.<>c__DisplayClass18_0.<<MessageReceived>b__0>d.MoveNext()

This workaround works:

@code {
    // The following dependency prevents HeadOutlet from getting trimmed away
    [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(HeadOutlet))]
    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
        }
    }
}

Jinjinov avatar Dec 22 '22 13:12 Jinjinov

Well I tink no to change this if so let's talk about it

Lover2023 avatar Dec 24 '22 12:12 Lover2023

I am thinking of not changing it I believe that I shouldn't be change for Burt fuel reasons

Lover2023 avatar Dec 24 '22 12:12 Lover2023

Using Blazor Server .NET 7 having the same issue when trying to trim:

Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
      An unhandled exception has occurred while executing the request.
      System.MissingMethodException: Cannot dynamically create an instance of type 'Microsoft.AspNetCore.Components.Web.HeadOutlet'. Reason: No parameterless constructor defined.

Mark-Phillipson avatar Jan 01 '23 13:01 Mark-Phillipson

@Mark-Phillipson I fixed this issue like this in Maui Blazor. Not sure about Blazor server though.

    // The following dependency prevents HeadOutlet from getting trimmed away
    [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(HeadOutlet))]
    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
        }
    }

Jinjinov avatar Jan 01 '23 16:01 Jinjinov

I don' see how Blazor server can be supported for trimming when most of ASP.NET Core isn't.

davidfowl avatar Jan 01 '23 16:01 davidfowl

FYI - It looks like we put a similar work around for Blazor WASM here:

https://github.com/dotnet/aspnetcore/blob/1d04387cf3b68636f8ade0118334f87ae5f56f7d/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostBuilder.cs#L41-L44

eerhardt avatar Jan 03 '23 16:01 eerhardt

I can disable trimming for Linux and Android, but there is no way to disable trimming for iOS and macOS

You can do this for iOS and Mac Catalyst:

<PropertyGroup>
    <MouchLink>None</MtouchLink>
</PropertyGroup>

We're updating the error message to suggest this in a future release.

rolfbjarne avatar Feb 20 '23 12:02 rolfbjarne

Going to track progress for this topic in the following issue https://github.com/dotnet/aspnetcore/issues/51598 if you are interested, upvote that issue instead.

javiercn avatar Oct 24 '23 11:10 javiercn

Closing in favor of the issue @javiercn linked above, which we will be prioritizing for .NET 9.

mkArtakMSFT avatar Dec 12 '23 18:12 mkArtakMSFT