Is there a way to resolve nested interfaces on DTO

2019-08-06 02:21发布

问题:

We are having an issue with the Razor view engine not resolving nested interfaces. Sample code:

public interface IDto
{
    Guid Id {get;set;}
}

public interface IUserDto: IDto
{
  string Username {get;set;}
}

//The view
@model IUserDto

//pukes on this line
@Html.DisplayFor(u => u.Id)

Should we be using concrete models on our views? Is the Razor view engine not capable of using multiple interfaces per model?

回答1:

This was a change in ASP.NET MVC 3 that I already brought to the attention of Microsoft (this scenario worked on ASP.NET MVC 1 and 2).

Here's their official answer:

Hi Darin (and others),

This was a deliberate change that we introduced to ASP.NET MVC 3 that was the result of a trade-off between having better support for inherited models or better support for models that implement interfaces. We ended up favoring inherited models, which from our experience is a more common approach.

The fundamental problem is that when an interface is implemented by a class that the class doesn't really inherit any of the members of the interface. The key here is that because it doesn't inherit the members of the interface, it also does not inherit the metadata on those members.

Thanks, The ASP.NET Team

Now to the point

Should we be using concrete models on our views?

Not necessary. You could still use interfaces on your main views, but then have editor/display templates with concrete types. At runtime based on the actual type of the view model the framework will pick the correct template where you will have the concrete type and it will resolve the Id property.

Another possibility is to use abstract classes instead of interfaces (beurk I know :-) typically Microsoftish)