正确使用Interfaces这种方式,还有更好的选择吗?

时间:2010-10-17 07:27:45

标签: c# asp.net-mvc-2 interface

嘿伙计们,今天早上5点,我正在做一些代码......当这个出现时:

public interface IViewModel { }

public interface IToViewModel<T> where T : IViewModel { }

public static class MvcExtensions
{
    public static T ToViewModel<T>(this IToViewModel<T> self)
        where T : IViewModel
    {
        var instance = Activator.CreateInstance<T>();

        //this line just copys the properties with the same name from one object to another
        self.Reflected().CopyMatchingPropertiesTo(instance /*destiny*/);

        return instance;
    }

}

我对此代码的观点是这样的:

public partial class UserInfo : IToViewModel<UserInfoViewModel> { }

public class UserInfoViewModel : IViewModel
{
    [DisplayName("UserId")]
    public Guid UserId { get; set; }

    [DisplayName("User name")]
    public string Username { get; set; }

    [DisplayName("Email address")]
    public string Email { get; set; }
}

public ActionResult Index(string username)
{
    UserInfo userInfo = UserInfoHelper.Load(username);

    UserInfoViewModel userInfoViewModel = userInfo.ToViewModel();            

    return View(userInfoViewModel);
}

Oks,这段代码运行正常,np。

但我的问题是关于接口的使用......

我的目标是将EntityFramework对象转换为ViewModel以与ASP MVC视图一起使用 在没有做太多参数传递的情况下,我在接口中找到了一种方式来说明每个对象是什么,它们执行的是什么。

对我来说看起来很奇怪的是这些接口里面没有方法。

那你们怎么想呢? 关于它的某些地方有一些很酷的博文/ doc /等吗? 你知道怎么做得更好吗? 我现在应该去睡觉吗?

另外,.Net带来了很多新的做事方式......比如linq,lambda,扩展方法,表达树......有没有关于这些东西的“良好实践”的研究?

我认为这是巨大的,并且在您解决问题的时候让您的大脑有所不同......我希望看到人们在想什么/做什么。

提前致谢

1 个答案:

答案 0 :(得分:2)

我想这可能是标记接口与功能接口的问题。我通常不喜欢标记界面,但我明白你为什么要这样使用它。

就个人而言,我认为你应该有一个重载的构造函数:

public class UserViewModel
{
  // Constructor used in model binding.
  public UserViewModel() { }

  // Constructor used for mapping.
  public UserViewModel(UserEntity entity)
  {

  }
}

我有这个偏好,因为它干净地定义了我需要的依赖性。我知道你失去了将它应用于任何类型的一些保真度,但我认为它更清洁。

另一种选择是走AutoMapper路线。使用AutoMapper,您可以轻松地在一种类型和另一种类型之间进行映射......例如

Mapper.CreateMap<UserEntity, UserViewModel>();

public static TTarget Map<TSource, TTarget>(this TSource instance)
{
  return Mapper.Map<TSource, TTarget>(instance);
}

var user = DataContext.Users.Where(u => u.Username == "Matt").Single();
return user.Map<UserViewModel>();

现在,您必须提前创建特定的映射,但是您的扩展方法可以用于您为其创建映射的任何类型。 AutoMapper的默认行为是在匹配的属性之间进行映射,但您也可以获取特定的方式和地图属性。

相关问题