Search code examples
asp.net-mvcasp.net-core

How to differentiate between two assemblies in a Razor view?


I have an extension method:

.ToDescription()

This method exists in a MyExtensions class in the My.Methods namespace, in an assembly named MyAssembly1. I also have other extension methods in a MyExtensions class in the My.Methods namespace, but in a different assembly named MyAssembly2.

Both of these assemblies are referenced in my project. MyAssembly2.My.Methods.MyExtensions contains no .ToDescription() method.

I wish to use the .ToDescription() extension method in a Razor view, but I'm getting an ambiguous reference error:

The type 'MyExtensions' exists in both 'MyAssembly1' and 'MyAssembly2'

Is there a way to tell a Razor view which assembly to use, when both the namespaces and the classes are the same?

Note: I did attempt some research on this, but due to the complex nature of the question, no usable results were returned.


Solution

  • I tried to reproduce your issue,it's ok in .net 8(what's your .net version?),you could try update the .net version.

    A workaround for you to fix Error CS0433 in Razor View:

    In project file:

    <ItemGroup>
        <ProjectReference Include="..\ClassLibrary1\ClassLibrary1.csproj" >
          <Aliases>CustomTypes</Aliases>
        </ProjectReference>
        <ProjectReference Include="..\ClassLibrary2\ClassLibrary2.csproj" />
      </ItemGroup>
    

    In program.cs:

    extern alias CustomTypes;
    global using _MyExtension = CustomTypes::My.Methods;
    

    In your razor view:

    @using _MyExtension
    

    Here's the document related Error CS0433,hopes help