Home > OS >  Why is the using alias directive not resolving the conflict between imported class and class in pare
Why is the using alias directive not resolving the conflict between imported class and class in pare

Time:11-26

I am working with a code base which includes the following class

namespace Api.Data.Models;

// legacy db class entry
public class Log
{
}

and in another class I am constructing a model binder which includes some logging

using Log = Serilog.Log;

namespace Api.Data.Models.Binding;

public class ModelBinder : IModelBinder 
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        Log.Information("Trying to call Log.Information"); 
        // This cannot resolve symbol Information as it is still pointing at Api.Data.Models.Log
    }
}

I'm not sure if I am trying to do the impossible or if I'm missing something, but why is the aliasing not resolving my name conflict issue in this scenario?

There are other ways to solve my specific problem in the code base but I couldn't find a post or question about this particular case online and hence the question.

CodePudding user response:

The main problem is the namespace nomenclature here.

Your Log class is declared in namespace Api.Data.Models namespace. and ModelBinder is declared in the namespace Api.Data.Models.Binding;.

Api.Data.Models prefix is the same for both the namespaces and that is why it considers your Log class when calling Log.Information("Trying to call Log.Information");.

So you could have a different namespace and your issue will be resolved. like for your Log class use namespace Api.Data.Models.Logs.

Edit: As mentioned in the comment, If you can not change the Log file then you could change the namespace of ModelBinder class or use a different alias for Serilog.Log. Thank you @Fildorfor pointing it out.

Based on OP's comment the local namespace class always takes precedence over the imported class of the same name regardless of aliasing.

  • Related