3

An existing web application is using .NET Framework 4.5.1. The project has the setting MvcBuildViews set to true. The project also uses a Prepend extension method for IEnumerable<T>.

Stuff breaks miraculously after merely installing the .NET Framework 4.7.1 Developer Pack.

Even though the web.config still targets framework 4.5.1:

<system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
    ...

at runtime the view appears to be compiled using 4.7.1, leading to an ambiguous call (because 4.7.1 has its own Prepend extension):

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0121: The call is ambiguous between the following methods or properties: 'System.Linq.Enumerable.Prepend(System.Collections.Generic.IEnumerable, TSource)' and 'WebApplication2.EnumerableExtensions.Prepend(System.Collections.Generic.IEnumerable, T)'

How do I solve this issue without upgrading all applications to 4.7.1? It should be possible to use 4.5.1 and 4.7.1 side-by-side, right?!

Reproduction steps:

  1. Create a new ASP.NET Web Application (.NET Framework) project for .NET Framework 4.5.1;

  2. Update package Microsoft.CodeDom.Providers.DotNetCompilerPlatform to version 1.0.8;

  3. Add this class:

    public static class EnumerableExtensions
    {
        public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, T item)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
    
            return Iterator();
    
            IEnumerable<T> Iterator()
            {
                yield return item;
                foreach (var i in source)
                {
                    yield return i;
                }
            }
        }
    }
    
  4. Change About.cshtml to this:

    @{
        ViewBag.Title = "About";
        var a = new List<string> { "a", "b" };
        a.Prepend("c");
    }
    <h2>@ViewBag.Title.</h2>
    <h3>@ViewBag.Message</h3>
    
    <p>Use this area to provide additional information.</p>
    @foreach (var s in a)
    {
        <h4>@s</h4>
    }
    
  5. Run the application from Visual Studio (IIS Express) and see a working About page;

  6. Install .NET Framework 4.7.1 Dev Pack;

  7. Run the application again and see it fail...

Issue reported at Microsoft Developer Community: https://developercommunity.visualstudio.com/content/problem/150969/mvc-view-compilation-using-wrong-framework.html

Community
  • 1
  • 1
AroglDarthu
  • 1,021
  • 8
  • 17

0 Answers0